summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--api/Android.bp62
-rw-r--r--api/ApiDocs.bp2
-rw-r--r--api/api.go5
-rw-r--r--cmds/idmap2/libidmap2/ResourceContainer.cpp16
-rw-r--r--core/api/current.txt102
-rw-r--r--core/api/test-current.txt10
-rw-r--r--core/java/android/adaptiveauth/OWNERS2
-rw-r--r--core/java/android/app/PropertyInvalidatedCache.java284
-rw-r--r--core/java/android/app/admin/flags/flags.aconfig7
-rw-r--r--core/java/android/app/appfunctions/AppFunctionException.aidl21
-rw-r--r--core/java/android/app/appfunctions/AppFunctionException.java260
-rw-r--r--core/java/android/app/appfunctions/AppFunctionManager.java38
-rw-r--r--core/java/android/app/appfunctions/AppFunctionRuntimeMetadata.java4
-rw-r--r--core/java/android/app/appfunctions/AppFunctionService.java44
-rw-r--r--core/java/android/app/appfunctions/AppFunctionStaticMetadataHelper.java2
-rw-r--r--core/java/android/app/appfunctions/ExecuteAppFunctionResponse.java280
-rw-r--r--core/java/android/app/appfunctions/GenericDocumentWrapper.java11
-rw-r--r--core/java/android/app/appfunctions/IExecuteAppFunctionCallback.aidl4
-rw-r--r--core/java/android/app/appfunctions/SafeOneTimeExecuteAppFunctionCallback.java42
-rw-r--r--core/java/android/app/assist/AssistContent.java15
-rw-r--r--core/java/android/app/performance.aconfig17
-rw-r--r--core/java/android/content/ClipData.java1
-rw-r--r--core/java/android/content/Intent.java290
-rw-r--r--core/java/android/hardware/camera2/CameraMetadata.java26
-rw-r--r--core/java/android/hardware/camera2/CaptureRequest.java40
-rw-r--r--core/java/android/hardware/camera2/CaptureResult.java40
-rw-r--r--core/java/android/hardware/input/KeyGestureEvent.java8
-rw-r--r--core/java/android/hardware/input/input_framework.aconfig15
-rw-r--r--core/java/android/os/Bundle.java2
-rw-r--r--core/java/android/os/flags.aconfig9
-rw-r--r--core/java/android/permission/flags.aconfig3
-rw-r--r--core/java/android/provider/Settings.java13
-rw-r--r--core/java/android/security/flags.aconfig7
-rw-r--r--core/java/android/service/settings/preferences/ISettingsPreferenceService.aidl18
-rw-r--r--core/java/android/service/settings/preferences/SettingsPreferenceService.java201
-rw-r--r--core/java/android/service/settings/preferences/SettingsPreferenceServiceClient.java248
-rw-r--r--core/java/android/telephony/PhoneStateListener.java6
-rw-r--r--core/java/android/telephony/TelephonyCallback.java34
-rw-r--r--core/java/android/telephony/TelephonyRegistryManager.java19
-rw-r--r--core/java/android/view/KeyEvent.java89
-rw-r--r--core/java/android/view/SurfaceControl.java2
-rw-r--r--core/java/android/view/accessibility/AccessibilityNodeInfo.java18
-rw-r--r--core/java/android/view/accessibility/flags/accessibility_flags.aconfig7
-rw-r--r--core/java/android/view/autofill/AutofillFeatureFlags.java84
-rw-r--r--core/java/android/view/inputmethod/flags.aconfig8
-rw-r--r--core/java/android/window/DesktopModeFlags.java3
-rw-r--r--core/java/com/android/internal/telephony/IPhoneStateListener.aidl2
-rw-r--r--core/java/com/android/internal/telephony/ITelephonyRegistry.aidl3
-rw-r--r--core/java/com/android/internal/widget/NotificationProgressDrawable.java49
-rw-r--r--core/jni/android_hardware_input_InputWindowHandle.cpp165
-rw-r--r--core/jni/android_hardware_input_InputWindowHandle.h21
-rw-r--r--core/jni/android_view_SurfaceControl.cpp12
-rw-r--r--core/proto/android/providers/settings/secure.proto1
-rw-r--r--core/tests/coretests/src/android/app/PropertyInvalidatedCacheTests.java79
-rw-r--r--core/tests/coretests/src/android/content/IntentTest.java43
-rw-r--r--data/etc/privapp-permissions-platform.xml3
-rw-r--r--data/keyboards/Generic.kl42
-rw-r--r--libs/WindowManager/Shell/res/layout/desktop_mode_window_decor_handle_menu.xml4
-rw-r--r--libs/WindowManager/Shell/res/values/strings.xml2
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/apptoweb/AppToWebUtils.kt18
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java5
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipAppOpsListener.kt12
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java11
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java7
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java7
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopImmersiveController.kt94
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt11
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt8
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksLimiter.kt6
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java44
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java7
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipTaskOrganizer.java7
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java174
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentsTransitionHandler.java152
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/StageCoordinator.java16
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java8
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java12
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecoration.java37
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt77
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuAnimator.kt41
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuImageButton.kt7
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/AppHandleViewHolder.kt5
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/common/pip/PipAppOpsListenerTest.java191
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopImmersiveControllerTest.kt63
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopRepositoryTest.kt22
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksLimiterTest.kt28
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java10
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorationTests.java27
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/HandleMenuTest.kt9
-rw-r--r--libs/appfunctions/api/current.txt46
-rw-r--r--libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionException.java211
-rw-r--r--libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionManager.java23
-rw-r--r--libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionService.java28
-rw-r--r--libs/appfunctions/java/com/android/extensions/appfunctions/ExecuteAppFunctionResponse.java284
-rw-r--r--libs/appfunctions/java/com/android/extensions/appfunctions/SidecarConverter.java43
-rw-r--r--libs/appfunctions/tests/src/com/android/extensions/appfunctions/tests/SidecarConverterTest.kt73
-rw-r--r--media/java/android/media/MediaCas.java9
-rw-r--r--media/java/android/media/flags/media_better_together.aconfig2
-rw-r--r--media/java/android/media/quality/AmbientBacklightSettings.java1
-rw-r--r--media/java/android/media/quality/IMediaQualityManager.aidl18
-rw-r--r--media/java/android/media/quality/IPictureProfileCallback.aidl9
-rw-r--r--media/java/android/media/quality/MediaQualityManager.java176
-rw-r--r--media/java/android/media/quality/ParamCapability.java6
-rw-r--r--media/java/android/media/quality/PictureProfile.java47
-rw-r--r--nfc/api/system-current.txt22
-rw-r--r--nfc/java/android/nfc/INfcOemExtensionCallback.aidl2
-rw-r--r--nfc/java/android/nfc/NfcOemExtension.java12
-rw-r--r--nfc/java/android/nfc/OemLogItems.aidl19
-rw-r--r--nfc/java/android/nfc/OemLogItems.java325
-rw-r--r--packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppPreference.java15
-rw-r--r--packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppSwitchPreference.java15
-rw-r--r--packages/SettingsLib/IntroPreference/Android.bp1
-rw-r--r--packages/SettingsLib/SelectorWithWidgetPreference/Android.bp2
-rw-r--r--packages/SettingsLib/SettingsTheme/res/layout-v35/settingslib_expressive_preference_icon_frame.xml2
-rw-r--r--packages/SettingsLib/SettingsTheme/res/values-v35/styles_preference_expressive.xml13
-rw-r--r--packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java1
-rw-r--r--packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java3
-rw-r--r--packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java3
-rw-r--r--packages/Shell/AndroidManifest.xml4
-rw-r--r--packages/Shell/src/com/android/shell/BugreportProgressService.java2
-rw-r--r--packages/SystemUI/README.md2
-rw-r--r--packages/SystemUI/aconfig/systemui.aconfig10
-rw-r--r--packages/SystemUI/compose/features/src/com/android/systemui/statusbar/phone/SystemUIDialogFactoryExt.kt6
-rw-r--r--packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/Element.kt40
-rw-r--r--packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/ElementTest.kt54
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorTest.kt65
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardOcclusionInteractorTest.kt51
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryTest.kt2
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryTest.kt61
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/QuickAccessWalletTileTest.java34
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt28
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt14
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadePositionRepositoryTest.kt81
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImplTest.kt85
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculatorTest.kt49
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt72
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModelTest.kt143
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositorySwitcherTest.kt13
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/user/data/repository/UserRepositoryImplTest.kt5
-rw-r--r--packages/SystemUI/src/com/android/keyguard/ClockEventController.kt16
-rw-r--r--packages/SystemUI/src/com/android/systemui/authentication/data/repository/AuthenticationRepository.kt25
-rw-r--r--packages/SystemUI/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractor.kt18
-rw-r--r--packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt56
-rw-r--r--packages/SystemUI/src/com/android/systemui/deviceentry/DeviceEntryModule.kt12
-rw-r--r--packages/SystemUI/src/com/android/systemui/deviceentry/data/repository/DeviceEntryRepository.kt6
-rw-r--r--packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractor.kt221
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/transitions/ClockSizeTransition.kt25
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactory.kt5
-rw-r--r--packages/SystemUI/src/com/android/systemui/power/domain/interactor/PowerInteractor.kt14
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepository.kt51
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/panels/domain/backup/QSPreferencesBackupHelper.kt28
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/tiles/QuickAccessWalletTile.java10
-rw-r--r--packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt26
-rw-r--r--packages/SystemUI/src/com/android/systemui/shade/ShadePrimaryDisplayCommand.kt56
-rw-r--r--packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadePositionRepository.kt65
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImpl.java25
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiPickerTrackerFactory.kt15
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/LockScreenMinimalismCoordinator.kt23
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculator.kt58
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/MobileInputLogger.kt39
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt6
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt40
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt10
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt54
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt34
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt6
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt314
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/StatusBarPolicyModule.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/user/data/repository/UserRepository.kt83
-rw-r--r--packages/SystemUI/src/com/android/systemui/user/data/repository/UserSwitcherRepository.kt13
-rw-r--r--packages/SystemUI/src/com/android/systemui/wallet/ui/WalletScreenController.java14
-rw-r--r--packages/SystemUI/src/com/android/systemui/wallet/ui/WalletView.java5
-rw-r--r--packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt4
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/LegacyMediaDataManagerImplTest.kt13
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/MediaDataProcessorTest.kt21
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt18
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt131
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/wallet/ui/WalletScreenControllerTest.java39
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/authentication/data/repository/FakeAuthenticationRepository.kt30
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/repository/FakeDeviceEntryRepository.kt4
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorKosmos.kt28
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryKosmos.kt20
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryKosmos.kt6
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt1
-rw-r--r--services/accessibility/java/com/android/server/accessibility/AccessibilityInputFilter.java60
-rw-r--r--services/accessibility/java/com/android/server/accessibility/magnification/MagnificationController.java77
-rw-r--r--services/appfunctions/java/com/android/server/appfunctions/AppFunctionManagerServiceImpl.java64
-rw-r--r--services/appfunctions/java/com/android/server/appfunctions/RunAppFunctionServiceCallback.java26
-rw-r--r--services/backup/java/com/android/server/backup/UserBackupManagerService.java3
-rw-r--r--services/backup/java/com/android/server/backup/utils/BackupEligibilityRules.java7
-rw-r--r--services/core/Android.bp1
-rw-r--r--services/core/java/com/android/server/TelephonyRegistry.java62
-rw-r--r--services/core/java/com/android/server/adaptiveauth/OWNERS1
-rw-r--r--services/core/java/com/android/server/am/ActivityManagerService.java35
-rw-r--r--services/core/java/com/android/server/am/BroadcastController.java4
-rw-r--r--services/core/java/com/android/server/am/BroadcastRecord.java149
-rw-r--r--services/core/java/com/android/server/am/SettingsToPropertiesMapper.java7
-rw-r--r--services/core/java/com/android/server/am/broadcasts_flags.aconfig8
-rw-r--r--services/core/java/com/android/server/audio/AudioService.java23
-rw-r--r--services/core/java/com/android/server/biometrics/BiometricService.java69
-rw-r--r--services/core/java/com/android/server/input/InputGestureManager.java6
-rw-r--r--services/core/java/com/android/server/input/KeyGestureController.java26
-rw-r--r--services/core/java/com/android/server/media/quality/MediaQualityService.java24
-rw-r--r--services/core/java/com/android/server/notification/GroupHelper.java37
-rw-r--r--services/core/java/com/android/server/notification/ManagedServices.java28
-rw-r--r--services/core/java/com/android/server/policy/PhoneWindowManager.java38
-rw-r--r--services/core/java/com/android/server/policy/WindowWakeUpPolicy.java37
-rw-r--r--services/core/java/com/android/server/security/adaptiveauthentication/AdaptiveAuthenticationService.java (renamed from services/core/java/com/android/server/adaptiveauth/AdaptiveAuthService.java)10
-rw-r--r--services/core/java/com/android/server/security/adaptiveauthentication/OWNERS3
-rw-r--r--services/core/java/com/android/server/wm/BackgroundActivityStartController.java36
-rw-r--r--services/core/java/com/android/server/wm/BackgroundLaunchProcessController.java7
-rw-r--r--services/core/java/com/android/server/wm/Transition.java40
-rw-r--r--services/core/java/com/android/server/wm/TransitionController.java18
-rw-r--r--services/core/java/com/android/server/wm/WindowOrganizerController.java51
-rw-r--r--services/java/com/android/server/SystemServer.java6
-rw-r--r--services/tests/mockingservicestests/Android.bp1
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/am/ActivityManagerServiceTest.java12
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/am/BaseBroadcastQueueTest.java11
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueModernImplTest.java384
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueTest.java170
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/am/BroadcastRecordTest.java292
-rw-r--r--services/tests/servicestests/AndroidManifest.xml1
-rw-r--r--services/tests/servicestests/src/com/android/server/accessibility/magnification/MagnificationControllerTest.java88
-rw-r--r--services/tests/servicestests/src/com/android/server/adaptiveauth/OWNERS1
-rw-r--r--services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java90
-rw-r--r--services/tests/servicestests/src/com/android/server/security/adaptiveauthentication/AdaptiveAuthenticationServiceTest.java (renamed from services/tests/servicestests/src/com/android/server/adaptiveauth/AdaptiveAuthServiceTest.java)19
-rw-r--r--services/tests/servicestests/src/com/android/server/security/adaptiveauthentication/OWNERS1
-rw-r--r--services/tests/uiservicestests/src/com/android/server/UiServiceTestCase.java4
-rw-r--r--services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java69
-rw-r--r--services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java31
-rw-r--r--services/tests/wmtests/src/com/android/server/policy/ModifierShortcutTests.java12
-rw-r--r--services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java4
-rw-r--r--services/tests/wmtests/src/com/android/server/policy/WindowWakeUpPolicyTests.java95
-rw-r--r--telephony/java/android/telephony/satellite/EarfcnRange.aidl19
-rw-r--r--telephony/java/android/telephony/satellite/EarfcnRange.java124
-rw-r--r--telephony/java/android/telephony/satellite/ISatelliteCommunicationAllowedStateCallback.aidl12
-rw-r--r--telephony/java/android/telephony/satellite/SatelliteAccessConfiguration.aidl19
-rw-r--r--telephony/java/android/telephony/satellite/SatelliteAccessConfiguration.java122
-rw-r--r--telephony/java/android/telephony/satellite/SatelliteCommunicationAllowedStateCallback.java14
-rw-r--r--telephony/java/android/telephony/satellite/SatelliteInfo.aidl19
-rw-r--r--telephony/java/android/telephony/satellite/SatelliteInfo.java169
-rw-r--r--telephony/java/android/telephony/satellite/SatelliteManager.java86
-rw-r--r--telephony/java/android/telephony/satellite/SatellitePosition.aidl19
-rw-r--r--telephony/java/android/telephony/satellite/SatellitePosition.java114
-rw-r--r--telephony/java/com/android/internal/telephony/ITelephony.aidl12
-rw-r--r--tests/FlickerTests/test-apps/app-helpers/src/com/android/server/wm/flicker/helpers/DesktopModeAppHelper.kt4
-rw-r--r--tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt48
248 files changed, 8433 insertions, 2481 deletions
diff --git a/api/Android.bp b/api/Android.bp
index 0ac85e28de1a..cdc5cd120956 100644
--- a/api/Android.bp
+++ b/api/Android.bp
@@ -127,27 +127,54 @@ combined_apis {
}),
}
+// Create a single file containing the latest released version of the whole
+// Android public API.
+java_genrule {
+ name: "android.api.merged.public.latest",
+ srcs: [
+ ":android.api.combined.public.latest",
+ ],
+ out: ["public-latest.txt"],
+ tools: ["metalava"],
+ cmd: metalava_cmd + " merge-signatures --format=2.0 $(in) --out $(out)",
+}
+
+// Make sure that the Android public API is compatible with the
+// previously released public API.
java_genrule {
name: "frameworks-base-api-current-compat",
srcs: [
- ":android.api.public.latest",
+ ":android.api.merged.public.latest",
":android-incompatibilities.api.public.latest",
":frameworks-base-api-current.txt",
],
out: ["updated-baseline.txt"],
tools: ["metalava"],
cmd: metalava_cmd +
- "--check-compatibility:api:released $(location :android.api.public.latest) " +
+ "--check-compatibility:api:released $(location :android.api.merged.public.latest) " +
"--baseline:compatibility:released $(location :android-incompatibilities.api.public.latest) " +
"--update-baseline:compatibility:released $(genDir)/updated-baseline.txt " +
"$(location :frameworks-base-api-current.txt)",
}
+// Create a single file containing the latest released version of the whole
+// Android system API.
+java_genrule {
+ name: "android.api.merged.system.latest",
+ srcs: [
+ ":android.api.combined.system.latest",
+ ],
+ out: ["system-latest.txt"],
+ tools: ["metalava"],
+ cmd: metalava_cmd + " merge-signatures --format=2.0 $(in) --out $(out)",
+}
+
+// Make sure that the Android system API is compatible with the
+// previously released system API.
java_genrule {
name: "frameworks-base-api-system-current-compat",
srcs: [
- ":android.api.public.latest",
- ":android.api.system.latest",
+ ":android.api.merged.system.latest",
":android-incompatibilities.api.system.latest",
":frameworks-base-api-current.txt",
":frameworks-base-api-system-current.txt",
@@ -155,20 +182,31 @@ java_genrule {
out: ["updated-baseline.txt"],
tools: ["metalava"],
cmd: metalava_cmd +
- "--check-compatibility:api:released $(location :android.api.public.latest) " +
- "--check-compatibility:api:released $(location :android.api.system.latest) " +
+ "--check-compatibility:api:released $(location :android.api.merged.system.latest) " +
"--baseline:compatibility:released $(location :android-incompatibilities.api.system.latest) " +
"--update-baseline:compatibility:released $(genDir)/updated-baseline.txt " +
"$(location :frameworks-base-api-current.txt) " +
"$(location :frameworks-base-api-system-current.txt)",
}
+// Create a single file containing the latest released version of the whole
+// Android module-lib API.
+java_genrule {
+ name: "android.api.merged.module-lib.latest",
+ srcs: [
+ ":android.api.combined.module-lib.latest",
+ ],
+ out: ["module-lib-latest.txt"],
+ tools: ["metalava"],
+ cmd: metalava_cmd + " merge-signatures --format=2.0 $(in) --out $(out)",
+}
+
+// Make sure that the Android module-lib API is compatible with the
+// previously released module-lib API.
java_genrule {
name: "frameworks-base-api-module-lib-current-compat",
srcs: [
- ":android.api.public.latest",
- ":android.api.system.latest",
- ":android.api.module-lib.latest",
+ ":android.api.merged.module-lib.latest",
":android-incompatibilities.api.module-lib.latest",
":frameworks-base-api-current.txt",
":frameworks-base-api-system-current.txt",
@@ -177,9 +215,7 @@ java_genrule {
out: ["updated-baseline.txt"],
tools: ["metalava"],
cmd: metalava_cmd +
- "--check-compatibility:api:released $(location :android.api.public.latest) " +
- "--check-compatibility:api:released $(location :android.api.system.latest) " +
- "--check-compatibility:api:released $(location :android.api.module-lib.latest) " +
+ "--check-compatibility:api:released $(location :android.api.merged.module-lib.latest) " +
"--baseline:compatibility:released $(location :android-incompatibilities.api.module-lib.latest) " +
"--update-baseline:compatibility:released $(genDir)/updated-baseline.txt " +
"$(location :frameworks-base-api-current.txt) " +
@@ -194,7 +230,7 @@ java_genrule {
cmd: "$(location merge_zips) $(out) $(in)",
srcs: [
":api-stubs-docs-non-updatable{.exportable}",
- ":all-modules-public-stubs-source",
+ ":all-modules-public-stubs-source-exportable",
],
visibility: ["//visibility:private"], // Used by make module in //development, mind
}
diff --git a/api/ApiDocs.bp b/api/ApiDocs.bp
index e8fcf4b2b32d..1ebe0cdfabd7 100644
--- a/api/ApiDocs.bp
+++ b/api/ApiDocs.bp
@@ -129,7 +129,7 @@ droidstubs {
droidstubs {
name: "framework-doc-stubs",
defaults: ["android-non-updatable-doc-stubs-defaults"],
- srcs: [":all-modules-public-stubs-source"],
+ srcs: [":all-modules-public-stubs-source-exportable"],
api_levels_module: "api_versions_public",
aidl: {
include_dirs: [
diff --git a/api/api.go b/api/api.go
index f32bdc32f75d..5ca24de1b46a 100644
--- a/api/api.go
+++ b/api/api.go
@@ -429,8 +429,9 @@ func createMergedFrameworkSystemServerExportableStubs(ctx android.LoadHookContex
func createPublicStubsSourceFilegroup(ctx android.LoadHookContext, modules proptools.Configurable[[]string]) {
props := fgProps{}
- props.Name = proptools.StringPtr("all-modules-public-stubs-source")
- props.Device_common_srcs = createSrcs(modules, "{.public.stubs.source}")
+ props.Name = proptools.StringPtr("all-modules-public-stubs-source-exportable")
+ transformConfigurableArray(modules, "", ".stubs.source")
+ props.Device_common_srcs = createSrcs(modules, "{.exportable}")
props.Visibility = []string{"//frameworks/base"}
ctx.CreateModule(android.FileGroupFactory, &props)
}
diff --git a/cmds/idmap2/libidmap2/ResourceContainer.cpp b/cmds/idmap2/libidmap2/ResourceContainer.cpp
index 3c0e118bbfe7..57ae3548123b 100644
--- a/cmds/idmap2/libidmap2/ResourceContainer.cpp
+++ b/cmds/idmap2/libidmap2/ResourceContainer.cpp
@@ -17,6 +17,7 @@
#include "idmap2/ResourceContainer.h"
#include <memory>
+#include <mutex>
#include <string>
#include <utility>
#include <vector>
@@ -296,7 +297,7 @@ struct ResState {
} // namespace
struct ApkResourceContainer : public TargetResourceContainer, public OverlayResourceContainer {
- static Result<std::unique_ptr<ApkResourceContainer>> FromPath(const std::string& path);
+ static Result<std::unique_ptr<ApkResourceContainer>> FromPath(std::string path);
// inherited from TargetResourceContainer
Result<bool> DefinesOverlayable() const override;
@@ -320,6 +321,7 @@ struct ApkResourceContainer : public TargetResourceContainer, public OverlayReso
Result<const ResState*> GetState() const;
ZipAssetsProvider* GetZipAssets() const;
+ mutable std::mutex state_lock_;
mutable std::variant<std::unique_ptr<ZipAssetsProvider>, ResState> state_;
std::string path_;
};
@@ -330,16 +332,17 @@ ApkResourceContainer::ApkResourceContainer(std::unique_ptr<ZipAssetsProvider> zi
}
Result<std::unique_ptr<ApkResourceContainer>> ApkResourceContainer::FromPath(
- const std::string& path) {
+ std::string path) {
auto zip_assets = ZipAssetsProvider::Create(path, 0 /* flags */);
if (zip_assets == nullptr) {
return Error("failed to load zip assets");
}
return std::unique_ptr<ApkResourceContainer>(
- new ApkResourceContainer(std::move(zip_assets), path));
+ new ApkResourceContainer(std::move(zip_assets), std::move(path)));
}
Result<const ResState*> ApkResourceContainer::GetState() const {
+ std::lock_guard lock(state_lock_);
if (auto state = std::get_if<ResState>(&state_); state != nullptr) {
return state;
}
@@ -355,6 +358,7 @@ Result<const ResState*> ApkResourceContainer::GetState() const {
}
ZipAssetsProvider* ApkResourceContainer::GetZipAssets() const {
+ std::lock_guard lock(state_lock_);
if (auto zip = std::get_if<std::unique_ptr<ZipAssetsProvider>>(&state_); zip != nullptr) {
return zip->get();
}
@@ -427,7 +431,7 @@ Result<std::string> ApkResourceContainer::GetResourceName(ResourceId id) const {
Result<std::unique_ptr<TargetResourceContainer>> TargetResourceContainer::FromPath(
std::string path) {
- auto result = ApkResourceContainer::FromPath(path);
+ auto result = ApkResourceContainer::FromPath(std::move(path));
if (!result) {
return result.GetError();
}
@@ -438,7 +442,7 @@ Result<std::unique_ptr<OverlayResourceContainer>> OverlayResourceContainer::From
std::string path) {
// Load the path as a fabricated overlay if the file magic indicates this is a fabricated overlay.
if (android::IsFabricatedOverlay(path)) {
- auto result = FabricatedOverlayContainer::FromPath(path);
+ auto result = FabricatedOverlayContainer::FromPath(std::move(path));
if (!result) {
return result.GetError();
}
@@ -446,7 +450,7 @@ Result<std::unique_ptr<OverlayResourceContainer>> OverlayResourceContainer::From
}
// Fallback to loading the container as an APK.
- auto result = ApkResourceContainer::FromPath(path);
+ auto result = ApkResourceContainer::FromPath(std::move(path));
if (!result) {
return result.GetError();
}
diff --git a/core/api/current.txt b/core/api/current.txt
index 46d8de7c3794..2f5bde9d37f2 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -8792,8 +8792,31 @@ package android.app.admin {
package android.app.appfunctions {
+ @FlaggedApi("android.app.appfunctions.flags.enable_app_function_manager") public final class AppFunctionException extends java.lang.Exception implements android.os.Parcelable {
+ ctor public AppFunctionException(int, @Nullable String);
+ ctor public AppFunctionException(int, @Nullable String, @NonNull android.os.Bundle);
+ method public int describeContents();
+ method public int getErrorCategory();
+ method public int getErrorCode();
+ method @Nullable public String getErrorMessage();
+ method @NonNull public android.os.Bundle getExtras();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.app.appfunctions.AppFunctionException> CREATOR;
+ field public static final int ERROR_APP_UNKNOWN_ERROR = 3000; // 0xbb8
+ field public static final int ERROR_CANCELLED = 2001; // 0x7d1
+ field public static final int ERROR_CATEGORY_APP = 3; // 0x3
+ field public static final int ERROR_CATEGORY_REQUEST_ERROR = 1; // 0x1
+ field public static final int ERROR_CATEGORY_SYSTEM = 2; // 0x2
+ field public static final int ERROR_CATEGORY_UNKNOWN = 0; // 0x0
+ field public static final int ERROR_DENIED = 1000; // 0x3e8
+ field public static final int ERROR_DISABLED = 1002; // 0x3ea
+ field public static final int ERROR_FUNCTION_NOT_FOUND = 1003; // 0x3eb
+ field public static final int ERROR_INVALID_ARGUMENT = 1001; // 0x3e9
+ field public static final int ERROR_SYSTEM_ERROR = 2000; // 0x7d0
+ }
+
@FlaggedApi("android.app.appfunctions.flags.enable_app_function_manager") public final class AppFunctionManager {
- method @RequiresPermission(anyOf={"android.permission.EXECUTE_APP_FUNCTIONS_TRUSTED", "android.permission.EXECUTE_APP_FUNCTIONS"}, conditional=true) public void executeAppFunction(@NonNull android.app.appfunctions.ExecuteAppFunctionRequest, @NonNull java.util.concurrent.Executor, @NonNull android.os.CancellationSignal, @NonNull java.util.function.Consumer<android.app.appfunctions.ExecuteAppFunctionResponse>);
+ method @RequiresPermission(anyOf={"android.permission.EXECUTE_APP_FUNCTIONS_TRUSTED", "android.permission.EXECUTE_APP_FUNCTIONS"}, conditional=true) public void executeAppFunction(@NonNull android.app.appfunctions.ExecuteAppFunctionRequest, @NonNull java.util.concurrent.Executor, @NonNull android.os.CancellationSignal, @NonNull android.os.OutcomeReceiver<android.app.appfunctions.ExecuteAppFunctionResponse,android.app.appfunctions.AppFunctionException>);
method @RequiresPermission(anyOf={"android.permission.EXECUTE_APP_FUNCTIONS_TRUSTED", "android.permission.EXECUTE_APP_FUNCTIONS"}, conditional=true) public void isAppFunctionEnabled(@NonNull String, @NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Boolean,java.lang.Exception>);
method public void isAppFunctionEnabled(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Boolean,java.lang.Exception>);
method public void setAppFunctionEnabled(@NonNull String, int, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,java.lang.Exception>);
@@ -8805,7 +8828,7 @@ package android.app.appfunctions {
@FlaggedApi("android.app.appfunctions.flags.enable_app_function_manager") public abstract class AppFunctionService extends android.app.Service {
ctor public AppFunctionService();
method @NonNull public final android.os.IBinder onBind(@Nullable android.content.Intent);
- method @MainThread public abstract void onExecuteFunction(@NonNull android.app.appfunctions.ExecuteAppFunctionRequest, @NonNull String, @NonNull android.os.CancellationSignal, @NonNull java.util.function.Consumer<android.app.appfunctions.ExecuteAppFunctionResponse>);
+ method @MainThread public abstract void onExecuteFunction(@NonNull android.app.appfunctions.ExecuteAppFunctionRequest, @NonNull String, @NonNull android.os.CancellationSignal, @NonNull android.os.OutcomeReceiver<android.app.appfunctions.ExecuteAppFunctionResponse,android.app.appfunctions.AppFunctionException>);
field @NonNull public static final String SERVICE_INTERFACE = "android.app.appfunctions.AppFunctionService";
}
@@ -8827,30 +8850,14 @@ package android.app.appfunctions {
}
@FlaggedApi("android.app.appfunctions.flags.enable_app_function_manager") public final class ExecuteAppFunctionResponse implements android.os.Parcelable {
+ ctor public ExecuteAppFunctionResponse(@NonNull android.app.appsearch.GenericDocument);
+ ctor public ExecuteAppFunctionResponse(@NonNull android.app.appsearch.GenericDocument, @NonNull android.os.Bundle);
method public int describeContents();
- method public int getErrorCategory();
- method @Nullable public String getErrorMessage();
method @NonNull public android.os.Bundle getExtras();
- method public int getResultCode();
method @NonNull public android.app.appsearch.GenericDocument getResultDocument();
- method public boolean isSuccess();
- method @FlaggedApi("android.app.appfunctions.flags.enable_app_function_manager") @NonNull public static android.app.appfunctions.ExecuteAppFunctionResponse newFailure(int, @Nullable String, @Nullable android.os.Bundle);
- method @FlaggedApi("android.app.appfunctions.flags.enable_app_function_manager") @NonNull public static android.app.appfunctions.ExecuteAppFunctionResponse newSuccess(@NonNull android.app.appsearch.GenericDocument, @Nullable android.os.Bundle);
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.app.appfunctions.ExecuteAppFunctionResponse> CREATOR;
- field public static final int ERROR_CATEGORY_APP = 3; // 0x3
- field public static final int ERROR_CATEGORY_REQUEST_ERROR = 1; // 0x1
- field public static final int ERROR_CATEGORY_SYSTEM = 2; // 0x2
- field public static final int ERROR_CATEGORY_UNKNOWN = 0; // 0x0
- field public static final String PROPERTY_RETURN_VALUE = "android_app_appfunctions_returnvalue";
- field public static final int RESULT_APP_UNKNOWN_ERROR = 3000; // 0xbb8
- field public static final int RESULT_CANCELLED = 2001; // 0x7d1
- field public static final int RESULT_DENIED = 1000; // 0x3e8
- field public static final int RESULT_DISABLED = 1002; // 0x3ea
- field public static final int RESULT_FUNCTION_NOT_FOUND = 1003; // 0x3eb
- field public static final int RESULT_INVALID_ARGUMENT = 1001; // 0x3e9
- field public static final int RESULT_OK = 0; // 0x0
- field public static final int RESULT_SYSTEM_ERROR = 2000; // 0x7d0
+ field public static final String PROPERTY_RETURN_VALUE = "androidAppfunctionsReturnValue";
}
}
@@ -8873,6 +8880,7 @@ package android.app.assist {
method public void setWebUri(android.net.Uri);
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.app.assist.AssistContent> CREATOR;
+ field @FlaggedApi("android.app.appfunctions.flags.enable_app_function_manager") public static final String EXTRA_APP_FUNCTION_DATA = "android.app.assist.extra.APP_FUNCTION_DATA";
}
public class AssistStructure implements android.os.Parcelable {
@@ -19775,6 +19783,8 @@ package android.hardware.camera2 {
field public static final int CONTROL_VIDEO_STABILIZATION_MODE_OFF = 0; // 0x0
field public static final int CONTROL_VIDEO_STABILIZATION_MODE_ON = 1; // 0x1
field public static final int CONTROL_VIDEO_STABILIZATION_MODE_PREVIEW_STABILIZATION = 2; // 0x2
+ field @FlaggedApi("com.android.internal.camera.flags.zoom_method") public static final int CONTROL_ZOOM_METHOD_AUTO = 0; // 0x0
+ field @FlaggedApi("com.android.internal.camera.flags.zoom_method") public static final int CONTROL_ZOOM_METHOD_ZOOM_RATIO = 1; // 0x1
field public static final int DISTORTION_CORRECTION_MODE_FAST = 1; // 0x1
field public static final int DISTORTION_CORRECTION_MODE_HIGH_QUALITY = 2; // 0x2
field public static final int DISTORTION_CORRECTION_MODE_OFF = 0; // 0x0
@@ -19982,6 +19992,7 @@ package android.hardware.camera2 {
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_SCENE_MODE;
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_SETTINGS_OVERRIDE;
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_VIDEO_STABILIZATION_MODE;
+ field @FlaggedApi("com.android.internal.camera.flags.zoom_method") @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> CONTROL_ZOOM_METHOD;
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Float> CONTROL_ZOOM_RATIO;
field @NonNull public static final android.os.Parcelable.Creator<android.hardware.camera2.CaptureRequest> CREATOR;
field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE;
@@ -20080,6 +20091,7 @@ package android.hardware.camera2 {
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_SCENE_MODE;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_SETTINGS_OVERRIDE;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_VIDEO_STABILIZATION_MODE;
+ field @FlaggedApi("com.android.internal.camera.flags.zoom_method") @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> CONTROL_ZOOM_METHOD;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> CONTROL_ZOOM_RATIO;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE;
field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> EDGE_MODE;
@@ -42151,6 +42163,25 @@ package android.service.settings.preferences {
method @NonNull public android.service.settings.preferences.SettingsPreferenceMetadata.Builder setWriteSensitivity(int);
}
+ @FlaggedApi("com.android.settingslib.flags.settings_catalyst") public abstract class SettingsPreferenceService extends android.app.Service {
+ ctor public SettingsPreferenceService();
+ method @NonNull public final android.os.IBinder onBind(@Nullable android.content.Intent);
+ method public abstract void onGetAllPreferenceMetadata(@NonNull android.service.settings.preferences.MetadataRequest, @NonNull android.os.OutcomeReceiver<android.service.settings.preferences.MetadataResult,java.lang.Exception>);
+ method public abstract void onGetPreferenceValue(@NonNull android.service.settings.preferences.GetValueRequest, @NonNull android.os.OutcomeReceiver<android.service.settings.preferences.GetValueResult,java.lang.Exception>);
+ method public abstract void onSetPreferenceValue(@NonNull android.service.settings.preferences.SetValueRequest, @NonNull android.os.OutcomeReceiver<android.service.settings.preferences.SetValueResult,java.lang.Exception>);
+ field public static final String ACTION_PREFERENCE_SERVICE = "android.service.settings.preferences.action.PREFERENCE_SERVICE";
+ }
+
+ @FlaggedApi("com.android.settingslib.flags.settings_catalyst") public class SettingsPreferenceServiceClient implements java.lang.AutoCloseable {
+ ctor public SettingsPreferenceServiceClient(@NonNull android.content.Context, @NonNull String);
+ method public void close();
+ method public void getAllPreferenceMetadata(@NonNull android.service.settings.preferences.MetadataRequest, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.service.settings.preferences.MetadataResult,java.lang.Exception>);
+ method public void getPreferenceValue(@NonNull android.service.settings.preferences.GetValueRequest, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.service.settings.preferences.GetValueResult,java.lang.Exception>);
+ method public void setPreferenceValue(@NonNull android.service.settings.preferences.SetValueRequest, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.service.settings.preferences.SetValueResult,java.lang.Exception>);
+ method public void start();
+ method public void stop();
+ }
+
@FlaggedApi("com.android.settingslib.flags.settings_catalyst") public final class SettingsPreferenceValue implements android.os.Parcelable {
method public int describeContents();
method public boolean getBooleanValue();
@@ -51996,6 +52027,7 @@ package android.view {
field public static final int KEYCODE_CHANNEL_DOWN = 167; // 0xa7
field public static final int KEYCODE_CHANNEL_UP = 166; // 0xa6
field public static final int KEYCODE_CLEAR = 28; // 0x1c
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_CLOSE = 321; // 0x141
field public static final int KEYCODE_COMMA = 55; // 0x37
field public static final int KEYCODE_CONTACTS = 207; // 0xcf
field public static final int KEYCODE_COPY = 278; // 0x116
@@ -52008,6 +52040,8 @@ package android.view {
field public static final int KEYCODE_DEMO_APP_2 = 302; // 0x12e
field public static final int KEYCODE_DEMO_APP_3 = 303; // 0x12f
field public static final int KEYCODE_DEMO_APP_4 = 304; // 0x130
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_DICTATE = 319; // 0x13f
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_DO_NOT_DISTURB = 322; // 0x142
field public static final int KEYCODE_DPAD_CENTER = 23; // 0x17
field public static final int KEYCODE_DPAD_DOWN = 20; // 0x14
field public static final int KEYCODE_DPAD_DOWN_LEFT = 269; // 0x10d
@@ -52020,7 +52054,7 @@ package android.view {
field public static final int KEYCODE_DVR = 173; // 0xad
field public static final int KEYCODE_E = 33; // 0x21
field public static final int KEYCODE_EISU = 212; // 0xd4
- field @FlaggedApi("com.android.hardware.input.emoji_and_screenshot_keycodes_available") public static final int KEYCODE_EMOJI_PICKER = 317; // 0x13d
+ field public static final int KEYCODE_EMOJI_PICKER = 317; // 0x13d
field public static final int KEYCODE_ENDCALL = 6; // 0x6
field public static final int KEYCODE_ENTER = 66; // 0x42
field public static final int KEYCODE_ENVELOPE = 65; // 0x41
@@ -52032,7 +52066,19 @@ package android.view {
field public static final int KEYCODE_F10 = 140; // 0x8c
field public static final int KEYCODE_F11 = 141; // 0x8d
field public static final int KEYCODE_F12 = 142; // 0x8e
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F13 = 326; // 0x146
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F14 = 327; // 0x147
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F15 = 328; // 0x148
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F16 = 329; // 0x149
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F17 = 330; // 0x14a
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F18 = 331; // 0x14b
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F19 = 332; // 0x14c
field public static final int KEYCODE_F2 = 132; // 0x84
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F20 = 333; // 0x14d
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F21 = 334; // 0x14e
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F22 = 335; // 0x14f
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F23 = 336; // 0x150
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_F24 = 337; // 0x151
field public static final int KEYCODE_F3 = 133; // 0x85
field public static final int KEYCODE_F4 = 134; // 0x86
field public static final int KEYCODE_F5 = 135; // 0x87
@@ -52047,6 +52093,7 @@ package android.view {
field public static final int KEYCODE_FOCUS = 80; // 0x50
field public static final int KEYCODE_FORWARD = 125; // 0x7d
field public static final int KEYCODE_FORWARD_DEL = 112; // 0x70
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_FULLSCREEN = 325; // 0x145
field public static final int KEYCODE_FUNCTION = 119; // 0x77
field public static final int KEYCODE_G = 35; // 0x23
field public static final int KEYCODE_GRAVE = 68; // 0x44
@@ -52070,6 +52117,7 @@ package android.view {
field public static final int KEYCODE_LANGUAGE_SWITCH = 204; // 0xcc
field public static final int KEYCODE_LAST_CHANNEL = 229; // 0xe5
field public static final int KEYCODE_LEFT_BRACKET = 71; // 0x47
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_LOCK = 324; // 0x144
field public static final int KEYCODE_M = 41; // 0x29
field public static final int KEYCODE_MACRO_1 = 313; // 0x139
field public static final int KEYCODE_MACRO_2 = 314; // 0x13a
@@ -52107,6 +52155,7 @@ package android.view {
field public static final int KEYCODE_NAVIGATE_NEXT = 261; // 0x105
field public static final int KEYCODE_NAVIGATE_OUT = 263; // 0x107
field public static final int KEYCODE_NAVIGATE_PREVIOUS = 260; // 0x104
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_NEW = 320; // 0x140
field public static final int KEYCODE_NOTIFICATION = 83; // 0x53
field public static final int KEYCODE_NUM = 78; // 0x4e
field public static final int KEYCODE_NUMPAD_0 = 144; // 0x90
@@ -52141,6 +52190,7 @@ package android.view {
field public static final int KEYCODE_PLUS = 81; // 0x51
field public static final int KEYCODE_POUND = 18; // 0x12
field public static final int KEYCODE_POWER = 26; // 0x1a
+ field @FlaggedApi("com.android.hardware.input.enable_new_25q2_keycodes") public static final int KEYCODE_PRINT = 323; // 0x143
field public static final int KEYCODE_PROFILE_SWITCH = 288; // 0x120
field public static final int KEYCODE_PROG_BLUE = 186; // 0xba
field public static final int KEYCODE_PROG_GREEN = 184; // 0xb8
@@ -52153,7 +52203,7 @@ package android.view {
field public static final int KEYCODE_RIGHT_BRACKET = 72; // 0x48
field public static final int KEYCODE_RO = 217; // 0xd9
field public static final int KEYCODE_S = 47; // 0x2f
- field @FlaggedApi("com.android.hardware.input.emoji_and_screenshot_keycodes_available") public static final int KEYCODE_SCREENSHOT = 318; // 0x13e
+ field public static final int KEYCODE_SCREENSHOT = 318; // 0x13e
field public static final int KEYCODE_SCROLL_LOCK = 116; // 0x74
field public static final int KEYCODE_SEARCH = 84; // 0x54
field public static final int KEYCODE_SEMICOLON = 74; // 0x4a
@@ -55607,7 +55657,7 @@ package android.view.accessibility {
method public android.os.Bundle getExtras();
method public CharSequence getHintText();
method public int getInputType();
- method public android.view.accessibility.AccessibilityNodeInfo getLabelFor();
+ method @Deprecated @FlaggedApi("android.view.accessibility.deprecate_ani_label_for_apis") public android.view.accessibility.AccessibilityNodeInfo getLabelFor();
method @Deprecated @FlaggedApi("android.view.accessibility.support_multiple_labeledby") public android.view.accessibility.AccessibilityNodeInfo getLabeledBy();
method @FlaggedApi("android.view.accessibility.support_multiple_labeledby") @NonNull public java.util.List<android.view.accessibility.AccessibilityNodeInfo> getLabeledByList();
method public int getLiveRegion();
@@ -55706,8 +55756,8 @@ package android.view.accessibility {
method public void setHintText(CharSequence);
method public void setImportantForAccessibility(boolean);
method public void setInputType(int);
- method public void setLabelFor(android.view.View);
- method public void setLabelFor(android.view.View, int);
+ method @Deprecated @FlaggedApi("android.view.accessibility.deprecate_ani_label_for_apis") public void setLabelFor(android.view.View);
+ method @Deprecated @FlaggedApi("android.view.accessibility.deprecate_ani_label_for_apis") public void setLabelFor(android.view.View, int);
method @Deprecated @FlaggedApi("android.view.accessibility.support_multiple_labeledby") public void setLabeledBy(android.view.View);
method @Deprecated @FlaggedApi("android.view.accessibility.support_multiple_labeledby") public void setLabeledBy(android.view.View, int);
method public void setLiveRegion(int);
diff --git a/core/api/test-current.txt b/core/api/test-current.txt
index 117351943587..3ca55b932e19 100644
--- a/core/api/test-current.txt
+++ b/core/api/test-current.txt
@@ -3247,6 +3247,14 @@ package android.service.quicksettings {
}
+package android.service.settings.preferences {
+
+ @FlaggedApi("com.android.settingslib.flags.settings_catalyst") public class SettingsPreferenceServiceClient implements java.lang.AutoCloseable {
+ ctor public SettingsPreferenceServiceClient(@NonNull android.content.Context, @NonNull String, boolean, @Nullable android.content.ServiceConnection);
+ }
+
+}
+
package android.service.voice {
public class AlwaysOnHotwordDetector implements android.service.voice.HotwordDetector {
@@ -3729,7 +3737,7 @@ package android.view {
method public final int getDisplayId();
method public final void setDisplayId(int);
field public static final int FLAG_IS_ACCESSIBILITY_EVENT = 2048; // 0x800
- field public static final int LAST_KEYCODE = 318; // 0x13e
+ field public static final int LAST_KEYCODE = 337; // 0x151
}
public final class KeyboardShortcutGroup implements android.os.Parcelable {
diff --git a/core/java/android/adaptiveauth/OWNERS b/core/java/android/adaptiveauth/OWNERS
index 0218a7835586..bc8efa92c16f 100644
--- a/core/java/android/adaptiveauth/OWNERS
+++ b/core/java/android/adaptiveauth/OWNERS
@@ -1 +1 @@
-include /services/core/java/com/android/server/adaptiveauth/OWNERS \ No newline at end of file
+include /services/core/java/com/android/server/security/adaptiveauthentication/OWNERS \ No newline at end of file
diff --git a/core/java/android/app/PropertyInvalidatedCache.java b/core/java/android/app/PropertyInvalidatedCache.java
index f432a22b14ac..1dc774285a32 100644
--- a/core/java/android/app/PropertyInvalidatedCache.java
+++ b/core/java/android/app/PropertyInvalidatedCache.java
@@ -32,7 +32,10 @@ import android.os.Process;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.util.ArrayMap;
+import android.util.ArraySet;
import android.util.Log;
+import android.util.SparseArray;
+import android.util.SparseBooleanArray;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -92,9 +95,6 @@ public class PropertyInvalidatedCache<Query, Result> {
* caching on behalf of other processes.
*/
public boolean shouldBypassCache(@NonNull Q query) {
- if(android.multiuser.Flags.propertyInvalidatedCacheBypassMismatchedUids()) {
- return Binder.getCallingUid() != Process.myUid();
- }
return false;
}
};
@@ -392,8 +392,213 @@ public class PropertyInvalidatedCache<Query, Result> {
}
}
+ /**
+ * An array of hash maps, indexed by calling UID. The class behaves a bit like a hash map
+ * except that it uses the calling UID internally.
+ */
+ private class CacheMap<Query, Result> {
+
+ // Create a new map for a UID, using the parent's configuration for max size.
+ private LinkedHashMap<Query, Result> createMap() {
+ return new LinkedHashMap<Query, Result>(
+ 2 /* start small */,
+ 0.75f /* default load factor */,
+ true /* LRU access order */) {
+ @GuardedBy("mLock")
+ @Override
+ protected boolean removeEldestEntry(Map.Entry eldest) {
+ final int size = size();
+ if (size > mHighWaterMark) {
+ mHighWaterMark = size;
+ }
+ if (size > mMaxEntries) {
+ mMissOverflow++;
+ return true;
+ }
+ return false;
+ }
+ };
+ }
+
+ // An array of maps, indexed by UID.
+ private final SparseArray<LinkedHashMap<Query, Result>> mCache = new SparseArray<>();
+
+ // If true, isolate the hash entries by calling UID. If this is false, allow the cache
+ // entries to be combined in a single hash map.
+ private final boolean mIsolated;
+
+ // Collect statistics.
+ private final boolean mStatistics;
+
+ // An array of booleans to indicate if a UID has been involved in a map access. A value
+ // exists for every UID that was ever involved during cache access. This is updated only
+ // if statistics are being collected.
+ private final SparseBooleanArray mUidSeen;
+
+ // A hash map that ignores the UID. This is used in look-aside fashion just for hit/miss
+ // statistics. This is updated only if statistics are being collected.
+ private final ArraySet<Query> mShadowCache;
+
+ // Shadow statistics. Only hits and misses need to be recorded. These are updated only
+ // if statistics are being collected. The "SelfHits" records hits when the UID is the
+ // process uid.
+ private int mShadowHits;
+ private int mShadowMisses;
+ private int mShadowSelfHits;
+
+ // The process UID.
+ private final int mSelfUid;
+
+ // True in test mode. In test mode, the cache uses Binder.getWorkSource() as the UID.
+ private final boolean mTestMode;
+
+ /**
+ * Create a CacheMap. UID isolation is enabled if the input parameter is true and if the
+ * isolation feature is enabled.
+ */
+ CacheMap(boolean isolate, boolean testMode) {
+ mIsolated = Flags.picIsolateCacheByUid() && isolate;
+ mStatistics = Flags.picIsolatedCacheStatistics() && mIsolated;
+ if (mStatistics) {
+ mUidSeen = new SparseBooleanArray();
+ mShadowCache = new ArraySet<>();
+ } else {
+ mUidSeen = null;
+ mShadowCache = null;
+ }
+ mSelfUid = Process.myUid();
+ mTestMode = testMode;
+ }
+
+ // Return the UID for this cache invocation. If uid isolation is disabled, the value of 0
+ // is returned, which effectively places all entries in a single hash map.
+ private int callerUid() {
+ if (!mIsolated) {
+ return 0;
+ } else if (mTestMode) {
+ return Binder.getCallingWorkSourceUid();
+ } else {
+ return Binder.getCallingUid();
+ }
+ }
+
+ /**
+ * Lookup an entry in the cache.
+ */
+ Result get(Query query) {
+ final int uid = callerUid();
+
+ // Shadow statistics
+ if (mStatistics) {
+ if (mShadowCache.contains(query)) {
+ mShadowHits++;
+ if (uid == mSelfUid) {
+ mShadowSelfHits++;
+ }
+ } else {
+ mShadowMisses++;
+ }
+ }
+
+ var map = mCache.get(uid);
+ if (map != null) {
+ return map.get(query);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Remove an entry from the cache.
+ */
+ void remove(Query query) {
+ final int uid = callerUid();
+ if (mStatistics) {
+ mShadowCache.remove(query);
+ }
+
+ var map = mCache.get(uid);
+ if (map != null) {
+ map.remove(query);
+ }
+ }
+
+ /**
+ * Record an entry in the cache.
+ */
+ void put(Query query, Result result) {
+ final int uid = callerUid();
+ if (mStatistics) {
+ mShadowCache.add(query);
+ mUidSeen.put(uid, true);
+ }
+
+ var map = mCache.get(uid);
+ if (map == null) {
+ map = createMap();
+ mCache.put(uid, map);
+ }
+ map.put(query, result);
+ }
+
+ /**
+ * Return the number of entries in the cache.
+ */
+ int size() {
+ int total = 0;
+ for (int i = 0; i < mCache.size(); i++) {
+ var map = mCache.valueAt(i);
+ total += map.size();
+ }
+ return total;
+ }
+
+ /**
+ * Clear the entries in the cache. Update the shadow statistics.
+ */
+ void clear() {
+ if (mStatistics) {
+ mShadowCache.clear();
+ }
+
+ mCache.clear();
+ }
+
+ // Dump basic statistics, if any are collected. Do nothing if statistics are not enabled.
+ void dump(PrintWriter pw) {
+ if (mStatistics) {
+ pw.println(formatSimple(" ShadowHits: %d, ShadowMisses: %d, ShadowSize: %d",
+ mShadowHits, mShadowMisses, mShadowCache.size()));
+ pw.println(formatSimple(" ShadowUids: %d, SelfUid: %d",
+ mUidSeen.size(), mShadowSelfHits));
+ }
+ }
+
+ // Dump detailed statistics
+ void dumpDetailed(PrintWriter pw) {
+ for (int i = 0; i < mCache.size(); i++) {
+ int uid = mCache.keyAt(i);
+ var map = mCache.valueAt(i);
+
+ Set<Map.Entry<Query, Result>> cacheEntries = map.entrySet();
+ if (cacheEntries.size() == 0) {
+ break;
+ }
+
+ pw.println(" Contents:");
+ pw.println(formatSimple(" Uid: %d\n", uid));
+ for (Map.Entry<Query, Result> entry : cacheEntries) {
+ String key = Objects.toString(entry.getKey());
+ String value = Objects.toString(entry.getValue());
+
+ pw.println(formatSimple(" Key: %s\n Value: %s\n", key, value));
+ }
+ }
+ }
+ }
+
@GuardedBy("mLock")
- private final LinkedHashMap<Query, Result> mCache;
+ private final CacheMap<Query, Result> mCache;
/**
* The nonce handler for this cache.
@@ -895,7 +1100,8 @@ public class PropertyInvalidatedCache<Query, Result> {
* is allowed to be null in the record constructor to facility reuse of Args instances.
* @hide
*/
- public static record Args(@NonNull String mModule, @Nullable String mApi, int mMaxEntries) {
+ public static record Args(@NonNull String mModule, @Nullable String mApi,
+ int mMaxEntries, boolean mIsolateUids, boolean mTestMode) {
// Validation: the module must be one of the known module strings and the maxEntries must
// be positive.
@@ -909,15 +1115,28 @@ public class PropertyInvalidatedCache<Query, Result> {
// which is not legal, but there is no reasonable default. Clients must call the api
// method to set the field properly.
public Args(@NonNull String module) {
- this(module, /* api */ null, /* maxEntries */ 32);
+ this(module,
+ null, // api
+ 32, // maxEntries
+ true, // isolateUids
+ false // testMode
+ );
}
public Args api(@NonNull String api) {
- return new Args(mModule, api, mMaxEntries);
+ return new Args(mModule, api, mMaxEntries, mIsolateUids, mTestMode);
}
public Args maxEntries(int val) {
- return new Args(mModule, mApi, val);
+ return new Args(mModule, mApi, val, mIsolateUids, mTestMode);
+ }
+
+ public Args isolateUids(boolean val) {
+ return new Args(mModule, mApi, mMaxEntries, val, mTestMode);
+ }
+
+ public Args testMode(boolean val) {
+ return new Args(mModule, mApi, mMaxEntries, mIsolateUids, val);
}
}
@@ -936,7 +1155,7 @@ public class PropertyInvalidatedCache<Query, Result> {
mCacheName = cacheName;
mNonce = getNonceHandler(mPropertyName);
mMaxEntries = args.mMaxEntries;
- mCache = createMap();
+ mCache = new CacheMap<>(args.mIsolateUids, args.mTestMode);
mComputer = (computer != null) ? computer : new DefaultComputer<>(this);
registerCache();
}
@@ -1006,28 +1225,6 @@ public class PropertyInvalidatedCache<Query, Result> {
this(new Args(module).maxEntries(maxEntries).api(api), cacheName, computer);
}
- // Create a map. This should be called only from the constructor.
- private LinkedHashMap<Query, Result> createMap() {
- return new LinkedHashMap<Query, Result>(
- 2 /* start small */,
- 0.75f /* default load factor */,
- true /* LRU access order */) {
- @GuardedBy("mLock")
- @Override
- protected boolean removeEldestEntry(Map.Entry eldest) {
- final int size = size();
- if (size > mHighWaterMark) {
- mHighWaterMark = size;
- }
- if (size > mMaxEntries) {
- mMissOverflow++;
- return true;
- }
- return false;
- }
- };
- }
-
/**
* Register the map in the global list. If the cache is disabled globally, disable it
* now. This method is only ever called from the constructor, which means no other thread has
@@ -1778,8 +1975,8 @@ public class PropertyInvalidatedCache<Query, Result> {
pw.println(formatSimple(" Cache Name: %s", cacheName()));
pw.println(formatSimple(" Property: %s", mPropertyName));
pw.println(formatSimple(
- " Hits: %d, Misses: %d, Skips: %d, Clears: %d",
- mHits, mMisses, getSkipsLocked(), mClears));
+ " Hits: %d, Misses: %d, Skips: %d, Clears: %d, Uids: %d",
+ mHits, mMisses, getSkipsLocked(), mClears, mCache.size()));
// Print all the skip reasons.
pw.format(" Skip-%s: %d", sNonceName[0], mSkips[0]);
@@ -1794,25 +1991,16 @@ public class PropertyInvalidatedCache<Query, Result> {
pw.println(formatSimple(
" Current Size: %d, Max Size: %d, HW Mark: %d, Overflows: %d",
mCache.size(), mMaxEntries, mHighWaterMark, mMissOverflow));
+ mCache.dump(pw);
pw.println(formatSimple(" Enabled: %s", mDisabled ? "false" : "true"));
- // No specific cache was requested. This is the default, and no details
- // should be dumped.
- if (!detailed) {
- return;
- }
- Set<Map.Entry<Query, Result>> cacheEntries = mCache.entrySet();
- if (cacheEntries.size() == 0) {
- return;
+ // Dump the contents of the cache.
+ if (detailed) {
+ mCache.dumpDetailed(pw);
}
- pw.println(" Contents:");
- for (Map.Entry<Query, Result> entry : cacheEntries) {
- String key = Objects.toString(entry.getKey());
- String value = Objects.toString(entry.getValue());
-
- pw.println(formatSimple(" Key: %s\n Value: %s\n", key, value));
- }
+ // Separator between caches.
+ pw.println("");
}
}
diff --git a/core/java/android/app/admin/flags/flags.aconfig b/core/java/android/app/admin/flags/flags.aconfig
index fee071b14016..be24bfa41e10 100644
--- a/core/java/android/app/admin/flags/flags.aconfig
+++ b/core/java/android/app/admin/flags/flags.aconfig
@@ -367,3 +367,10 @@ flag {
description: "Allows DPMS to enable or disable SupervisionService based on whether the device is being managed by the supervision role holder."
bug: "376213673"
}
+
+flag {
+ name: "split_create_managed_profile_enabled"
+ namespace: "enterprise"
+ description: "Split up existing create and provision managed profile API."
+ bug: "375382324"
+}
diff --git a/core/java/android/app/appfunctions/AppFunctionException.aidl b/core/java/android/app/appfunctions/AppFunctionException.aidl
new file mode 100644
index 000000000000..7d432243b1b2
--- /dev/null
+++ b/core/java/android/app/appfunctions/AppFunctionException.aidl
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2024 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.app.appfunctions;
+
+import android.app.appfunctions.AppFunctionException;
+
+parcelable AppFunctionException; \ No newline at end of file
diff --git a/core/java/android/app/appfunctions/AppFunctionException.java b/core/java/android/app/appfunctions/AppFunctionException.java
new file mode 100644
index 000000000000..d33b5055f9cc
--- /dev/null
+++ b/core/java/android/app/appfunctions/AppFunctionException.java
@@ -0,0 +1,260 @@
+/*
+ * Copyright (C) 2024 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.app.appfunctions;
+
+import static android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER;
+
+import android.annotation.FlaggedApi;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.os.Bundle;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.Objects;
+
+/** Represents an app function related errors. */
+@FlaggedApi(FLAG_ENABLE_APP_FUNCTION_MANAGER)
+public final class AppFunctionException extends Exception implements Parcelable {
+ /**
+ * The caller does not have the permission to execute an app function.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
+ */
+ public static final int ERROR_DENIED = 1000;
+
+ /**
+ * The caller supplied invalid arguments to the execution request.
+ *
+ * <p>This error may be considered similar to {@link IllegalArgumentException}.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
+ */
+ public static final int ERROR_INVALID_ARGUMENT = 1001;
+
+ /**
+ * The caller tried to execute a disabled app function.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
+ */
+ public static final int ERROR_DISABLED = 1002;
+
+ /**
+ * The caller tried to execute a function that does not exist.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
+ */
+ public static final int ERROR_FUNCTION_NOT_FOUND = 1003;
+
+ /**
+ * An internal unexpected error coming from the system.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_SYSTEM} category.
+ */
+ public static final int ERROR_SYSTEM_ERROR = 2000;
+
+ /**
+ * The operation was cancelled. Use this error code to report that a cancellation is done after
+ * receiving a cancellation signal.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_SYSTEM} category.
+ */
+ public static final int ERROR_CANCELLED = 2001;
+
+ /**
+ * An unknown error occurred while processing the call in the AppFunctionService.
+ *
+ * <p>This error is thrown when the service is connected in the remote application but an
+ * unexpected error is thrown from the bound application.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_APP} category.
+ */
+ public static final int ERROR_APP_UNKNOWN_ERROR = 3000;
+
+ /**
+ * The error category is unknown.
+ *
+ * <p>This is the default value for {@link #getErrorCategory}.
+ */
+ public static final int ERROR_CATEGORY_UNKNOWN = 0;
+
+ /**
+ * The error is caused by the app requesting a function execution.
+ *
+ * <p>For example, the caller provided invalid parameters in the execution request e.g. an
+ * invalid function ID.
+ *
+ * <p>Errors in the category fall in the range 1000-1999 inclusive.
+ */
+ public static final int ERROR_CATEGORY_REQUEST_ERROR = 1;
+
+ /**
+ * The error is caused by an issue in the system.
+ *
+ * <p>For example, the AppFunctionService implementation is not found by the system.
+ *
+ * <p>Errors in the category fall in the range 2000-2999 inclusive.
+ */
+ public static final int ERROR_CATEGORY_SYSTEM = 2;
+
+ /**
+ * The error is caused by the app providing the function.
+ *
+ * <p>For example, the app crashed when the system is executing the request.
+ *
+ * <p>Errors in the category fall in the range 3000-3999 inclusive.
+ */
+ public static final int ERROR_CATEGORY_APP = 3;
+
+ private final int mErrorCode;
+ @Nullable private final String mErrorMessage;
+ @NonNull private final Bundle mExtras;
+
+ /**
+ * @param errorCode The error code.
+ * @param errorMessage The error message.
+ */
+ public AppFunctionException(@ErrorCode int errorCode, @Nullable String errorMessage) {
+ this(errorCode, errorMessage, Bundle.EMPTY);
+ }
+
+ /**
+ * @param errorCode The error code.
+ * @param errorMessage The error message.
+ * @param extras The extras associated with this error.
+ */
+ public AppFunctionException(
+ @ErrorCode int errorCode, @Nullable String errorMessage, @NonNull Bundle extras) {
+ mErrorCode = errorCode;
+ mErrorMessage = errorMessage;
+ mExtras = Objects.requireNonNull(extras);
+ }
+
+ private AppFunctionException(@NonNull Parcel in) {
+ mErrorCode = in.readInt();
+ mErrorMessage = in.readString8();
+ mExtras = Objects.requireNonNull(in.readBundle(getClass().getClassLoader()));
+ }
+
+ /** Returns one of the {@code ERROR} constants. */
+ @ErrorCode
+ public int getErrorCode() {
+ return mErrorCode;
+ }
+
+ /** Returns the error message. */
+ @Nullable
+ public String getErrorMessage() {
+ return mErrorMessage;
+ }
+
+ /**
+ * Returns the error category.
+ *
+ * <p>This method categorizes errors based on their underlying cause, allowing developers to
+ * implement targeted error handling and provide more informative error messages to users. It
+ * maps ranges of error codes to specific error categories.
+ *
+ * <p>This method returns {@code ERROR_CATEGORY_UNKNOWN} if the error code does not belong to
+ * any error category.
+ *
+ * <p>See {@link ErrorCategory} for a complete list of error categories and their corresponding
+ * error code ranges.
+ */
+ @ErrorCategory
+ public int getErrorCategory() {
+ if (mErrorCode >= 1000 && mErrorCode < 2000) {
+ return ERROR_CATEGORY_REQUEST_ERROR;
+ }
+ if (mErrorCode >= 2000 && mErrorCode < 3000) {
+ return ERROR_CATEGORY_SYSTEM;
+ }
+ if (mErrorCode >= 3000 && mErrorCode < 4000) {
+ return ERROR_CATEGORY_APP;
+ }
+ return ERROR_CATEGORY_UNKNOWN;
+ }
+
+ /** Returns any extras associated with this error. */
+ @NonNull
+ public Bundle getExtras() {
+ return mExtras;
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(mErrorCode);
+ dest.writeString8(mErrorMessage);
+ dest.writeBundle(mExtras);
+ }
+
+ /**
+ * Error codes.
+ *
+ * @hide
+ */
+ @IntDef(
+ prefix = {"ERROR_"},
+ value = {
+ ERROR_DENIED,
+ ERROR_APP_UNKNOWN_ERROR,
+ ERROR_FUNCTION_NOT_FOUND,
+ ERROR_SYSTEM_ERROR,
+ ERROR_INVALID_ARGUMENT,
+ ERROR_DISABLED,
+ ERROR_CANCELLED
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface ErrorCode {}
+
+ /**
+ * Error categories.
+ *
+ * @hide
+ */
+ @IntDef(
+ prefix = {"ERROR_CATEGORY_"},
+ value = {
+ ERROR_CATEGORY_UNKNOWN,
+ ERROR_CATEGORY_REQUEST_ERROR,
+ ERROR_CATEGORY_APP,
+ ERROR_CATEGORY_SYSTEM
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface ErrorCategory {}
+
+ @NonNull
+ public static final Creator<AppFunctionException> CREATOR =
+ new Creator<>() {
+ @Override
+ public AppFunctionException createFromParcel(Parcel in) {
+ return new AppFunctionException(in);
+ }
+
+ @Override
+ public AppFunctionException[] newArray(int size) {
+ return new AppFunctionException[size];
+ }
+ };
+}
diff --git a/core/java/android/app/appfunctions/AppFunctionManager.java b/core/java/android/app/appfunctions/AppFunctionManager.java
index 5ddb590add4c..ed088fed41c2 100644
--- a/core/java/android/app/appfunctions/AppFunctionManager.java
+++ b/core/java/android/app/appfunctions/AppFunctionManager.java
@@ -16,7 +16,7 @@
package android.app.appfunctions;
-import static android.app.appfunctions.ExecuteAppFunctionResponse.getResultCode;
+import static android.app.appfunctions.AppFunctionException.ERROR_SYSTEM_ERROR;
import static android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER;
import android.Manifest;
@@ -39,7 +39,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Objects;
import java.util.concurrent.Executor;
-import java.util.function.Consumer;
/**
* Provides access to app functions.
@@ -147,16 +146,16 @@ public final class AppFunctionManager {
* @param request the request to execute the app function
* @param executor the executor to run the callback
* @param cancellationSignal the cancellation signal to cancel the execution.
- * @param callback the callback to receive the function execution result.
+ * @param callback the callback to receive the function execution result or error.
* <p>If the calling app does not own the app function or does not have {@code
* android.permission.EXECUTE_APP_FUNCTIONS_TRUSTED} or {@code
* android.permission.EXECUTE_APP_FUNCTIONS}, the execution result will contain {@code
- * ExecuteAppFunctionResponse.RESULT_DENIED}.
+ * AppFunctionException.ERROR_DENIED}.
* <p>If the caller only has {@code android.permission.EXECUTE_APP_FUNCTIONS} but the
* function requires {@code android.permission.EXECUTE_APP_FUNCTIONS_TRUSTED}, the execution
- * result will contain {@code ExecuteAppFunctionResponse.RESULT_DENIED}
+ * result will contain {@code AppFunctionException.ERROR_DENIED}
* <p>If the function requested for execution is disabled, then the execution result will
- * contain {@code ExecuteAppFunctionResponse.RESULT_DISABLED}
+ * contain {@code AppFunctionException.ERROR_DISABLED}
* <p>If the cancellation signal is issued, the operation is cancelled and no response is
* returned to the caller.
*/
@@ -171,7 +170,9 @@ public final class AppFunctionManager {
@NonNull ExecuteAppFunctionRequest request,
@NonNull @CallbackExecutor Executor executor,
@NonNull CancellationSignal cancellationSignal,
- @NonNull Consumer<ExecuteAppFunctionResponse> callback) {
+ @NonNull
+ OutcomeReceiver<ExecuteAppFunctionResponse, AppFunctionException>
+ callback) {
Objects.requireNonNull(request);
Objects.requireNonNull(executor);
Objects.requireNonNull(callback);
@@ -186,20 +187,25 @@ public final class AppFunctionManager {
aidlRequest,
new IExecuteAppFunctionCallback.Stub() {
@Override
- public void onResult(ExecuteAppFunctionResponse result) {
+ public void onSuccess(ExecuteAppFunctionResponse result) {
try {
- executor.execute(() -> callback.accept(result));
+ executor.execute(() -> callback.onResult(result));
} catch (RuntimeException e) {
// Ideally shouldn't happen since errors are wrapped into
- // the
- // response, but we catch it here for additional safety.
- callback.accept(
- ExecuteAppFunctionResponse.newFailure(
- getResultCode(e),
- e.getMessage(),
- /* extras= */ null));
+ // the response, but we catch it here for additional safety.
+ executor.execute(
+ () ->
+ callback.onError(
+ new AppFunctionException(
+ ERROR_SYSTEM_ERROR,
+ e.getMessage())));
}
}
+
+ @Override
+ public void onError(AppFunctionException exception) {
+ executor.execute(() -> callback.onError(exception));
+ }
});
if (cancellationTransport != null) {
cancellationSignal.setRemote(cancellationTransport);
diff --git a/core/java/android/app/appfunctions/AppFunctionRuntimeMetadata.java b/core/java/android/app/appfunctions/AppFunctionRuntimeMetadata.java
index 06d95f5270c3..3ddda228d145 100644
--- a/core/java/android/app/appfunctions/AppFunctionRuntimeMetadata.java
+++ b/core/java/android/app/appfunctions/AppFunctionRuntimeMetadata.java
@@ -213,9 +213,7 @@ public class AppFunctionRuntimeMetadata extends GenericDocument {
setEnabled(original.getEnabled());
}
- /**
- * Sets an indicator specifying the function enabled state.
- */
+ /** Sets an indicator specifying the function enabled state. */
@NonNull
public Builder setEnabled(@EnabledState int enabledState) {
if (enabledState != APP_FUNCTION_STATE_DEFAULT
diff --git a/core/java/android/app/appfunctions/AppFunctionService.java b/core/java/android/app/appfunctions/AppFunctionService.java
index 63d187aa11ef..85b6ab2b4e61 100644
--- a/core/java/android/app/appfunctions/AppFunctionService.java
+++ b/core/java/android/app/appfunctions/AppFunctionService.java
@@ -17,7 +17,6 @@
package android.app.appfunctions;
import static android.Manifest.permission.BIND_APP_FUNCTION_SERVICE;
-import static android.app.appfunctions.ExecuteAppFunctionResponse.getResultCode;
import static android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER;
import static android.content.pm.PackageManager.PERMISSION_DENIED;
@@ -32,10 +31,8 @@ import android.os.Binder;
import android.os.CancellationSignal;
import android.os.IBinder;
import android.os.ICancellationSignal;
+import android.os.OutcomeReceiver;
import android.os.RemoteException;
-import android.util.Log;
-
-import java.util.function.Consumer;
/**
* Abstract base class to provide app functions to the system.
@@ -80,7 +77,9 @@ public abstract class AppFunctionService extends Service {
@NonNull ExecuteAppFunctionRequest request,
@NonNull String callingPackage,
@NonNull CancellationSignal cancellationSignal,
- @NonNull Consumer<ExecuteAppFunctionResponse> callback);
+ @NonNull
+ OutcomeReceiver<ExecuteAppFunctionResponse, AppFunctionException>
+ callback);
}
/** @hide */
@@ -105,13 +104,22 @@ public abstract class AppFunctionService extends Service {
request,
callingPackage,
buildCancellationSignal(cancellationCallback),
- safeCallback::onResult);
+ new OutcomeReceiver<>() {
+ @Override
+ public void onResult(ExecuteAppFunctionResponse result) {
+ safeCallback.onResult(result);
+ }
+
+ @Override
+ public void onError(AppFunctionException exception) {
+ safeCallback.onError(exception);
+ }
+ });
} catch (Exception ex) {
// Apps should handle exceptions. But if they don't, report the error on
// behalf of them.
- safeCallback.onResult(
- ExecuteAppFunctionResponse.newFailure(
- getResultCode(ex), ex.getMessage(), /* extras= */ null));
+ safeCallback.onError(
+ new AppFunctionException(toErrorCode(ex), ex.getMessage()));
}
}
};
@@ -164,12 +172,26 @@ public abstract class AppFunctionService extends Service {
* @param request The function execution request.
* @param callingPackage The package name of the app that is requesting the execution.
* @param cancellationSignal A signal to cancel the execution.
- * @param callback A callback to report back the result.
+ * @param callback A callback to report back the result or error.
*/
@MainThread
public abstract void onExecuteFunction(
@NonNull ExecuteAppFunctionRequest request,
@NonNull String callingPackage,
@NonNull CancellationSignal cancellationSignal,
- @NonNull Consumer<ExecuteAppFunctionResponse> callback);
+ @NonNull
+ OutcomeReceiver<ExecuteAppFunctionResponse, AppFunctionException>
+ callback);
+
+ /**
+ * Returns result codes from throwable.
+ *
+ * @hide
+ */
+ private static @AppFunctionException.ErrorCode int toErrorCode(@NonNull Throwable t) {
+ if (t instanceof IllegalArgumentException) {
+ return AppFunctionException.ERROR_INVALID_ARGUMENT;
+ }
+ return AppFunctionException.ERROR_APP_UNKNOWN_ERROR;
+ }
}
diff --git a/core/java/android/app/appfunctions/AppFunctionStaticMetadataHelper.java b/core/java/android/app/appfunctions/AppFunctionStaticMetadataHelper.java
index a23f842e6eeb..1869d22ea080 100644
--- a/core/java/android/app/appfunctions/AppFunctionStaticMetadataHelper.java
+++ b/core/java/android/app/appfunctions/AppFunctionStaticMetadataHelper.java
@@ -38,7 +38,7 @@ public class AppFunctionStaticMetadataHelper {
public static final String STATIC_SCHEMA_TYPE = "AppFunctionStaticMetadata";
public static final String STATIC_PROPERTY_ENABLED_BY_DEFAULT = "enabledByDefault";
public static final String STATIC_PROPERTY_RESTRICT_CALLERS_WITH_EXECUTE_APP_FUNCTIONS =
- "restrictCallersWithExecuteAppFunctions";
+ "restrictCallersWithExecuteAppFunctions";
public static final String APP_FUNCTION_STATIC_NAMESPACE = "app_functions";
public static final String PROPERTY_FUNCTION_ID = "functionId";
diff --git a/core/java/android/app/appfunctions/ExecuteAppFunctionResponse.java b/core/java/android/app/appfunctions/ExecuteAppFunctionResponse.java
index ced4b553d641..acad43b782e5 100644
--- a/core/java/android/app/appfunctions/ExecuteAppFunctionResponse.java
+++ b/core/java/android/app/appfunctions/ExecuteAppFunctionResponse.java
@@ -19,16 +19,12 @@ package android.app.appfunctions;
import static android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER;
import android.annotation.FlaggedApi;
-import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.Nullable;
import android.app.appsearch.GenericDocument;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
import java.util.Objects;
/** The response to an app function execution. */
@@ -45,10 +41,7 @@ public final class ExecuteAppFunctionResponse implements Parcelable {
Bundle extras =
Objects.requireNonNull(
parcel.readBundle(Bundle.class.getClassLoader()));
- int resultCode = parcel.readInt();
- String errorMessage = parcel.readString8();
- return new ExecuteAppFunctionResponse(
- resultWrapper, extras, resultCode, errorMessage);
+ return new ExecuteAppFunctionResponse(resultWrapper.getValue(), extras);
}
@Override
@@ -71,113 +64,7 @@ public final class ExecuteAppFunctionResponse implements Parcelable {
*
* <p>See {@link #getResultDocument} for more information on extracting the return value.
*/
- public static final String PROPERTY_RETURN_VALUE = "android_app_appfunctions_returnvalue";
-
- /**
- * The call was successful.
- *
- * <p>This result code does not belong in an error category.
- */
- public static final int RESULT_OK = 0;
-
- /**
- * The caller does not have the permission to execute an app function.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
- */
- public static final int RESULT_DENIED = 1000;
-
- /**
- * The caller supplied invalid arguments to the execution request.
- *
- * <p>This error may be considered similar to {@link IllegalArgumentException}.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
- */
- public static final int RESULT_INVALID_ARGUMENT = 1001;
-
- /**
- * The caller tried to execute a disabled app function.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
- */
- public static final int RESULT_DISABLED = 1002;
-
- /**
- * The caller tried to execute a function that does not exist.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
- */
- public static final int RESULT_FUNCTION_NOT_FOUND = 1003;
-
- /**
- * An internal unexpected error coming from the system.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_SYSTEM} category.
- */
- public static final int RESULT_SYSTEM_ERROR = 2000;
-
- /**
- * The operation was cancelled. Use this error code to report that a cancellation is done after
- * receiving a cancellation signal.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_SYSTEM} category.
- */
- public static final int RESULT_CANCELLED = 2001;
-
- /**
- * An unknown error occurred while processing the call in the AppFunctionService.
- *
- * <p>This error is thrown when the service is connected in the remote application but an
- * unexpected error is thrown from the bound application.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_APP} category.
- */
- public static final int RESULT_APP_UNKNOWN_ERROR = 3000;
-
- /**
- * The error category is unknown.
- *
- * <p>This is the default value for {@link #getErrorCategory}.
- */
- public static final int ERROR_CATEGORY_UNKNOWN = 0;
-
- /**
- * The error is caused by the app requesting a function execution.
- *
- * <p>For example, the caller provided invalid parameters in the execution request e.g. an
- * invalid function ID.
- *
- * <p>Errors in the category fall in the range 1000-1999 inclusive.
- */
- public static final int ERROR_CATEGORY_REQUEST_ERROR = 1;
-
- /**
- * The error is caused by an issue in the system.
- *
- * <p>For example, the AppFunctionService implementation is not found by the system.
- *
- * <p>Errors in the category fall in the range 2000-2999 inclusive.
- */
- public static final int ERROR_CATEGORY_SYSTEM = 2;
-
- /**
- * The error is caused by the app providing the function.
- *
- * <p>For example, the app crashed when the system is executing the request.
- *
- * <p>Errors in the category fall in the range 3000-3999 inclusive.
- */
- public static final int ERROR_CATEGORY_APP = 3;
-
- /** The result code of the app function execution. */
- @ResultCode private final int mResultCode;
-
- /**
- * The error message associated with the result, if any. This is {@code null} if the result code
- * is {@link #RESULT_OK}.
- */
- @Nullable private final String mErrorMessage;
+ public static final String PROPERTY_RETURN_VALUE = "androidAppfunctionsReturnValue";
/**
* Returns the return value of the executed function.
@@ -192,103 +79,21 @@ public final class ExecuteAppFunctionResponse implements Parcelable {
/** Returns the additional metadata data relevant to this function execution response. */
@NonNull private final Bundle mExtras;
- private ExecuteAppFunctionResponse(
- @NonNull GenericDocumentWrapper resultDocumentWrapper,
- @NonNull Bundle extras,
- @ResultCode int resultCode,
- @Nullable String errorMessage) {
- mResultDocumentWrapper = Objects.requireNonNull(resultDocumentWrapper);
- mExtras = Objects.requireNonNull(extras);
- mResultCode = resultCode;
- mErrorMessage = errorMessage;
- }
-
/**
- * Returns result codes from throwable.
- *
- * @hide
- */
- @FlaggedApi(FLAG_ENABLE_APP_FUNCTION_MANAGER)
- static @ResultCode int getResultCode(@NonNull Throwable t) {
- if (t instanceof IllegalArgumentException) {
- return ExecuteAppFunctionResponse.RESULT_INVALID_ARGUMENT;
- }
- return ExecuteAppFunctionResponse.RESULT_APP_UNKNOWN_ERROR;
- }
-
- /**
- * Returns a successful response.
- *
* @param resultDocument The return value of the executed function.
- * @param extras The additional metadata for this function execution response.
*/
- @NonNull
- @FlaggedApi(FLAG_ENABLE_APP_FUNCTION_MANAGER)
- public static ExecuteAppFunctionResponse newSuccess(
- @NonNull GenericDocument resultDocument, @Nullable Bundle extras) {
- Objects.requireNonNull(resultDocument);
- Bundle actualExtras = getActualExtras(extras);
- GenericDocumentWrapper resultDocumentWrapper = new GenericDocumentWrapper(resultDocument);
-
- return new ExecuteAppFunctionResponse(
- resultDocumentWrapper, actualExtras, RESULT_OK, /* errorMessage= */ null);
+ public ExecuteAppFunctionResponse(@NonNull GenericDocument resultDocument) {
+ this(resultDocument, Bundle.EMPTY);
}
/**
- * Returns a failure response.
- *
- * @param resultCode The result code of the app function execution.
+ * @param resultDocument The return value of the executed function.
* @param extras The additional metadata for this function execution response.
- * @param errorMessage The error message associated with the result, if any.
- */
- @NonNull
- @FlaggedApi(FLAG_ENABLE_APP_FUNCTION_MANAGER)
- public static ExecuteAppFunctionResponse newFailure(
- @ResultCode int resultCode, @Nullable String errorMessage, @Nullable Bundle extras) {
- if (resultCode == RESULT_OK) {
- throw new IllegalArgumentException("resultCode must not be RESULT_OK");
- }
- Bundle actualExtras = getActualExtras(extras);
- GenericDocumentWrapper emptyWrapper =
- new GenericDocumentWrapper(new GenericDocument.Builder<>("", "", "").build());
- return new ExecuteAppFunctionResponse(emptyWrapper, actualExtras, resultCode, errorMessage);
- }
-
- private static Bundle getActualExtras(@Nullable Bundle extras) {
- if (extras == null) {
- return Bundle.EMPTY;
- }
- return extras;
- }
-
- /**
- * Returns the error category of the {@link ExecuteAppFunctionResponse}.
- *
- * <p>This method categorizes errors based on their underlying cause, allowing developers to
- * implement targeted error handling and provide more informative error messages to users. It
- * maps ranges of result codes to specific error categories.
- *
- * <p>When constructing a {@link #newFailure} response, use the appropriate result code value to
- * ensure correct categorization of the failed response.
- *
- * <p>This method returns {@code ERROR_CATEGORY_UNKNOWN} if the result code does not belong to
- * any error category, for example, in the case of a successful result with {@link #RESULT_OK}.
- *
- * <p>See {@link ErrorCategory} for a complete list of error categories and their corresponding
- * result code ranges.
*/
- @ErrorCategory
- public int getErrorCategory() {
- if (mResultCode >= 1000 && mResultCode < 2000) {
- return ERROR_CATEGORY_REQUEST_ERROR;
- }
- if (mResultCode >= 2000 && mResultCode < 3000) {
- return ERROR_CATEGORY_SYSTEM;
- }
- if (mResultCode >= 3000 && mResultCode < 4000) {
- return ERROR_CATEGORY_APP;
- }
- return ERROR_CATEGORY_UNKNOWN;
+ public ExecuteAppFunctionResponse(
+ @NonNull GenericDocument resultDocument, @NonNull Bundle extras) {
+ mResultDocumentWrapper = new GenericDocumentWrapper(Objects.requireNonNull(resultDocument));
+ mExtras = Objects.requireNonNull(extras);
}
/**
@@ -296,9 +101,6 @@ public final class ExecuteAppFunctionResponse implements Parcelable {
*
* <p>The {@link #PROPERTY_RETURN_VALUE} key can be used to obtain the return value.
*
- * <p>An empty document is returned if {@link #isSuccess} is {@code false} or if the executed
- * function does not produce a return value.
- *
* <p>Sample code for extracting the return value:
*
* <pre>
@@ -324,32 +126,6 @@ public final class ExecuteAppFunctionResponse implements Parcelable {
return mExtras;
}
- /**
- * Returns {@code true} if {@link #getResultCode} equals {@link
- * ExecuteAppFunctionResponse#RESULT_OK}.
- */
- public boolean isSuccess() {
- return getResultCode() == RESULT_OK;
- }
-
- /**
- * Returns one of the {@code RESULT} constants defined in {@link ExecuteAppFunctionResponse}.
- */
- @ResultCode
- public int getResultCode() {
- return mResultCode;
- }
-
- /**
- * Returns the error message associated with this result.
- *
- * <p>If {@link #isSuccess} is {@code true}, the error message is always {@code null}.
- */
- @Nullable
- public String getErrorMessage() {
- return mErrorMessage;
- }
-
@Override
public int describeContents() {
return 0;
@@ -359,43 +135,5 @@ public final class ExecuteAppFunctionResponse implements Parcelable {
public void writeToParcel(@NonNull Parcel dest, int flags) {
mResultDocumentWrapper.writeToParcel(dest, flags);
dest.writeBundle(mExtras);
- dest.writeInt(mResultCode);
- dest.writeString8(mErrorMessage);
}
-
- /**
- * Result codes.
- *
- * @hide
- */
- @IntDef(
- prefix = {"RESULT_"},
- value = {
- RESULT_OK,
- RESULT_DENIED,
- RESULT_APP_UNKNOWN_ERROR,
- RESULT_FUNCTION_NOT_FOUND,
- RESULT_SYSTEM_ERROR,
- RESULT_INVALID_ARGUMENT,
- RESULT_DISABLED,
- RESULT_CANCELLED
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface ResultCode {}
-
- /**
- * Error categories.
- *
- * @hide
- */
- @IntDef(
- prefix = {"ERROR_CATEGORY_"},
- value = {
- ERROR_CATEGORY_UNKNOWN,
- ERROR_CATEGORY_REQUEST_ERROR,
- ERROR_CATEGORY_APP,
- ERROR_CATEGORY_SYSTEM
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface ErrorCategory {}
}
diff --git a/core/java/android/app/appfunctions/GenericDocumentWrapper.java b/core/java/android/app/appfunctions/GenericDocumentWrapper.java
index b29b64e44d21..541ca7458efe 100644
--- a/core/java/android/app/appfunctions/GenericDocumentWrapper.java
+++ b/core/java/android/app/appfunctions/GenericDocumentWrapper.java
@@ -34,9 +34,9 @@ import java.util.Objects;
* <p>{#link {@link Parcel#writeBlob(byte[])}} could take care of whether to pass data via binder
* directly or Android shared memory if the data is large.
*
- * <p>This class performs lazy unparcelling. The `GenericDocument` is only unparcelled
- * from the underlying `Parcel` when {@link #getValue()} is called. This optimization
- * allows the system server to pass through the generic document, without unparcel and parcel it.
+ * <p>This class performs lazy unparcelling. The `GenericDocument` is only unparcelled from the
+ * underlying `Parcel` when {@link #getValue()} is called. This optimization allows the system
+ * server to pass through the generic document, without unparcel and parcel it.
*
* @hide
* @see Parcel#writeBlob(byte[])
@@ -45,8 +45,11 @@ public final class GenericDocumentWrapper implements Parcelable {
@Nullable
@GuardedBy("mLock")
private GenericDocument mGenericDocument;
+
@GuardedBy("mLock")
- @Nullable private Parcel mParcel;
+ @Nullable
+ private Parcel mParcel;
+
private final Object mLock = new Object();
public static final Creator<GenericDocumentWrapper> CREATOR =
diff --git a/core/java/android/app/appfunctions/IExecuteAppFunctionCallback.aidl b/core/java/android/app/appfunctions/IExecuteAppFunctionCallback.aidl
index 5323f9b627e3..69bbc0e5d275 100644
--- a/core/java/android/app/appfunctions/IExecuteAppFunctionCallback.aidl
+++ b/core/java/android/app/appfunctions/IExecuteAppFunctionCallback.aidl
@@ -17,8 +17,10 @@
package android.app.appfunctions;
import android.app.appfunctions.ExecuteAppFunctionResponse;
+import android.app.appfunctions.AppFunctionException;
/** {@hide} */
oneway interface IExecuteAppFunctionCallback {
- void onResult(in ExecuteAppFunctionResponse result);
+ void onSuccess(in ExecuteAppFunctionResponse result);
+ void onError(in AppFunctionException exception);
}
diff --git a/core/java/android/app/appfunctions/SafeOneTimeExecuteAppFunctionCallback.java b/core/java/android/app/appfunctions/SafeOneTimeExecuteAppFunctionCallback.java
index 00182447e9a8..2426daf5c9f2 100644
--- a/core/java/android/app/appfunctions/SafeOneTimeExecuteAppFunctionCallback.java
+++ b/core/java/android/app/appfunctions/SafeOneTimeExecuteAppFunctionCallback.java
@@ -17,17 +17,16 @@
package android.app.appfunctions;
import android.annotation.NonNull;
-import android.annotation.Nullable;
import android.os.RemoteException;
import android.util.Log;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.function.Consumer;
/**
* A wrapper of IExecuteAppFunctionCallback which swallows the {@link RemoteException}. This
- * callback is intended for one-time use only. Subsequent calls to onResult() will be ignored.
+ * callback is intended for one-time use only. Subsequent calls to onResult() or onError() will be
+ * ignored.
*
* @hide
*/
@@ -38,44 +37,41 @@ public class SafeOneTimeExecuteAppFunctionCallback {
@NonNull private final IExecuteAppFunctionCallback mCallback;
- @Nullable private final Consumer<ExecuteAppFunctionResponse> mOnDispatchCallback;
-
public SafeOneTimeExecuteAppFunctionCallback(@NonNull IExecuteAppFunctionCallback callback) {
- this(callback, /* onDispatchCallback= */ null);
- }
-
- /**
- * @param callback The callback to wrap.
- * @param onDispatchCallback An optional callback invoked after the wrapped callback has been
- * dispatched with a result. This callback receives the result that has been dispatched.
- */
- public SafeOneTimeExecuteAppFunctionCallback(
- @NonNull IExecuteAppFunctionCallback callback,
- @Nullable Consumer<ExecuteAppFunctionResponse> onDispatchCallback) {
mCallback = Objects.requireNonNull(callback);
- mOnDispatchCallback = onDispatchCallback;
}
/** Invoke wrapped callback with the result. */
public void onResult(@NonNull ExecuteAppFunctionResponse result) {
if (!mOnResultCalled.compareAndSet(false, true)) {
- Log.w(TAG, "Ignore subsequent calls to onResult()");
+ Log.w(TAG, "Ignore subsequent calls to onResult/onError()");
return;
}
try {
- mCallback.onResult(result);
+ mCallback.onSuccess(result);
} catch (RemoteException ex) {
// Failed to notify the other end. Ignore.
Log.w(TAG, "Failed to invoke the callback", ex);
}
- if (mOnDispatchCallback != null) {
- mOnDispatchCallback.accept(result);
+ }
+
+ /** Invoke wrapped callback with the error. */
+ public void onError(@NonNull AppFunctionException error) {
+ if (!mOnResultCalled.compareAndSet(false, true)) {
+ Log.w(TAG, "Ignore subsequent calls to onResult/onError()");
+ return;
+ }
+ try {
+ mCallback.onError(error);
+ } catch (RemoteException ex) {
+ // Failed to notify the other end. Ignore.
+ Log.w(TAG, "Failed to invoke the callback", ex);
}
}
/**
- * Disables this callback. Subsequent calls to {@link #onResult(ExecuteAppFunctionResponse)}
- * will be ignored.
+ * Disables this callback. Subsequent calls to {@link #onResult(ExecuteAppFunctionResponse)} or
+ * {@link #onError(AppFunctionException)} will be ignored.
*/
public void disable() {
mOnResultCalled.set(true);
diff --git a/core/java/android/app/assist/AssistContent.java b/core/java/android/app/assist/AssistContent.java
index a48868906487..43a46ba7885d 100644
--- a/core/java/android/app/assist/AssistContent.java
+++ b/core/java/android/app/assist/AssistContent.java
@@ -1,5 +1,6 @@
package android.app.assist;
+import android.annotation.FlaggedApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ClipData;
import android.content.Intent;
@@ -15,6 +16,20 @@ import android.os.Parcelable;
* {@link android.app.Activity#onProvideAssistContent Activity.onProvideAssistContent}.
*/
public class AssistContent implements Parcelable {
+ /**
+ * Extra for a {@link Bundle} that provides contextual AppFunction's information about the
+ * content currently being viewed in the application.
+ * <p>
+ * This extra can be optionally supplied in the {@link AssistContent#getExtras()} bundle.
+ * <p>
+ * The schema of the {@link Bundle} in this extra is defined in the AppFunction SDK.
+ *
+ * @see android.app.appfunctions.AppFunctionManager
+ */
+ @FlaggedApi(android.app.appfunctions.flags.Flags.FLAG_ENABLE_APP_FUNCTION_MANAGER)
+ public static final String EXTRA_APP_FUNCTION_DATA =
+ "android.app.assist.extra.APP_FUNCTION_DATA";
+
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
private boolean mIsAppProvidedIntent = false;
private boolean mIsAppProvidedWebUri = false;
diff --git a/core/java/android/app/performance.aconfig b/core/java/android/app/performance.aconfig
index f51f748bc71f..61b53f97fea1 100644
--- a/core/java/android/app/performance.aconfig
+++ b/core/java/android/app/performance.aconfig
@@ -18,3 +18,20 @@ flag {
description: "Enforce PropertyInvalidatedCache.setTestMode() protocol"
bug: "360897450"
}
+
+flag {
+ namespace: "system_performance"
+ name: "pic_isolate_cache_by_uid"
+ is_fixed_read_only: true
+ description: "Ensure that different UIDs use different caches"
+ bug: "373752556"
+}
+
+flag {
+ namespace: "system_performance"
+ name: "pic_isolated_cache_statistics"
+ is_fixed_read_only: true
+ description: "Collects statistics for cache UID isolation strategies"
+ bug: "373752556"
+}
+
diff --git a/core/java/android/content/ClipData.java b/core/java/android/content/ClipData.java
index cc57dc05d6b1..ff0bb25bbccc 100644
--- a/core/java/android/content/ClipData.java
+++ b/core/java/android/content/ClipData.java
@@ -398,7 +398,6 @@ public class ClipData implements Parcelable {
* Retrieve the raw Intent contained in this Item.
*/
public Intent getIntent() {
- Intent.maybeMarkAsMissingCreatorToken(mIntent);
return mIntent;
}
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index c054b79f617e..6fa5a9b82858 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -87,7 +87,6 @@ import android.util.AttributeSet;
import android.util.Log;
import android.util.proto.ProtoOutputStream;
-import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.XmlUtils;
import com.android.modules.expresslog.Counter;
@@ -109,7 +108,6 @@ import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.TimeZone;
-import java.util.function.Consumer;
/**
* An intent is an abstract description of an operation to be performed. It
@@ -894,20 +892,6 @@ public class Intent implements Parcelable, Cloneable {
public static void maybeMarkAsMissingCreatorToken(Object object) {
if (object instanceof Intent intent) {
maybeMarkAsMissingCreatorTokenInternal(intent);
- } else if (object instanceof Parcelable[] parcelables) {
- for (Parcelable p : parcelables) {
- if (p instanceof Intent intent) {
- maybeMarkAsMissingCreatorTokenInternal(intent);
- }
- }
- } else if (object instanceof ArrayList parcelables) {
- int N = parcelables.size();
- for (int i = 0; i < N; i++) {
- Object p = parcelables.get(i);
- if (p instanceof Intent intent) {
- maybeMarkAsMissingCreatorTokenInternal(intent);
- }
- }
}
}
@@ -12220,70 +12204,7 @@ public class Intent implements Parcelable, Cloneable {
// Stores a creator token for an intent embedded as an extra intent in a top level intent,
private IBinder mCreatorToken;
// Stores all extra keys whose values are intents for a top level intent.
- private ArraySet<NestedIntentKey> mNestedIntentKeys;
- }
-
- /**
- * @hide
- */
- public static class NestedIntentKey {
- /** @hide */
- @IntDef(flag = true, prefix = {"NESTED_INTENT_KEY_TYPE"}, value = {
- NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL,
- NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_ARRAY,
- NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_LIST,
- NESTED_INTENT_KEY_TYPE_CLIP_DATA,
- })
- @Retention(RetentionPolicy.SOURCE)
- private @interface NestedIntentKeyType {
- }
-
- /**
- * This flag indicates the key is for an extra parcel in mExtras.
- */
- private static final int NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL = 1 << 0;
-
- /**
- * This flag indicates the key is for an extra parcel array in mExtras and the index is the
- * index of that array.
- */
- private static final int NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_ARRAY = 1 << 1;
-
- /**
- * This flag indicates the key is for an extra parcel list in mExtras and the index is the
- * index of that list.
- */
- private static final int NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_LIST = 1 << 2;
-
- /**
- * This flag indicates the key is for an extra parcel in mClipData.mItems.
- */
- private static final int NESTED_INTENT_KEY_TYPE_CLIP_DATA = 1 << 3;
-
- // type can be a short or even byte. But then probably cannot use @IntDef?? Also not sure
- // if it is necessary.
- private final @NestedIntentKeyType int mType;
- private final String mKey;
- private final int mIndex;
-
- private NestedIntentKey(@NestedIntentKeyType int type, String key, int index) {
- this.mType = type;
- this.mKey = key;
- this.mIndex = index;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- NestedIntentKey that = (NestedIntentKey) o;
- return mType == that.mType && mIndex == that.mIndex && Objects.equals(mKey, that.mKey);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mType, mKey, mIndex);
- }
+ private ArraySet<String> mExtraIntentKeys;
}
private @Nullable CreatorTokenInfo mCreatorTokenInfo;
@@ -12306,9 +12227,8 @@ public class Intent implements Parcelable, Cloneable {
}
/** @hide */
- @VisibleForTesting
- public Set<NestedIntentKey> getExtraIntentKeys() {
- return mCreatorTokenInfo == null ? null : mCreatorTokenInfo.mNestedIntentKeys;
+ public Set<String> getExtraIntentKeys() {
+ return mCreatorTokenInfo == null ? null : mCreatorTokenInfo.mExtraIntentKeys;
}
/** @hide */
@@ -12326,168 +12246,45 @@ public class Intent implements Parcelable, Cloneable {
* @hide
*/
public void collectExtraIntentKeys() {
- if (preventIntentRedirect()) {
- collectNestedIntentKeysRecur(new ArraySet<>());
- }
- }
+ if (!preventIntentRedirect()) return;
- private void collectNestedIntentKeysRecur(Set<Intent> visited) {
- if (mExtras != null && !mExtras.isParcelled() && !mExtras.isEmpty()) {
+ if (mExtras != null && !mExtras.isEmpty()) {
for (String key : mExtras.keySet()) {
- Object value = mExtras.get(key);
-
- if (value instanceof Intent intent && !visited.contains(intent)) {
- handleNestedIntent(intent, visited, new NestedIntentKey(
- NestedIntentKey.NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL, key, 0));
- } else if (value instanceof Parcelable[] parcelables) {
- handleParcelableArray(parcelables, key, visited);
- } else if (value instanceof ArrayList<?> parcelables) {
- handleParcelableList(parcelables, key, visited);
- }
- }
- }
-
- if (mClipData != null) {
- for (int i = 0; i < mClipData.getItemCount(); i++) {
- Intent intent = mClipData.getItemAt(i).mIntent;
- if (intent != null && !visited.contains(intent)) {
- handleNestedIntent(intent, visited, new NestedIntentKey(
- NestedIntentKey.NESTED_INTENT_KEY_TYPE_CLIP_DATA, null, i));
+ if (mExtras.get(key) instanceof Intent) {
+ if (mCreatorTokenInfo == null) {
+ mCreatorTokenInfo = new CreatorTokenInfo();
+ }
+ if (mCreatorTokenInfo.mExtraIntentKeys == null) {
+ mCreatorTokenInfo.mExtraIntentKeys = new ArraySet<>();
+ }
+ mCreatorTokenInfo.mExtraIntentKeys.add(key);
}
}
}
}
- private void handleNestedIntent(Intent intent, Set<Intent> visited, NestedIntentKey key) {
- visited.add(intent);
- if (mCreatorTokenInfo == null) {
- mCreatorTokenInfo = new CreatorTokenInfo();
- }
- if (mCreatorTokenInfo.mNestedIntentKeys == null) {
- mCreatorTokenInfo.mNestedIntentKeys = new ArraySet<>();
- }
- mCreatorTokenInfo.mNestedIntentKeys.add(key);
- intent.collectNestedIntentKeysRecur(visited);
- }
-
- private void handleParcelableArray(Parcelable[] parcelables, String key, Set<Intent> visited) {
- for (int i = 0; i < parcelables.length; i++) {
- if (parcelables[i] instanceof Intent intent && !visited.contains(intent)) {
- handleNestedIntent(intent, visited, new NestedIntentKey(
- NestedIntentKey.NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_ARRAY, key, i));
- }
- }
- }
-
- private void handleParcelableList(ArrayList<?> parcelables, String key, Set<Intent> visited) {
- for (int i = 0; i < parcelables.size(); i++) {
- if (parcelables.get(i) instanceof Intent intent && !visited.contains(intent)) {
- handleNestedIntent(intent, visited, new NestedIntentKey(
- NestedIntentKey.NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_LIST, key, i));
- }
- }
- }
-
- private static final Consumer<Intent> CHECK_CREATOR_TOKEN_ACTION = intent -> {
- intent.mLocalFlags |= LOCAL_FLAG_TRUSTED_CREATOR_TOKEN_PRESENT;
- if (intent.mExtras != null) {
- intent.mExtras.enableTokenVerification();
- }
- };
-
/** @hide */
public void checkCreatorToken() {
- forEachNestedCreatorToken(CHECK_CREATOR_TOKEN_ACTION);
-
- if (mExtras != null) {
- // mark the bundle as intent extras after calls to getParcelable.
- // otherwise, the logic to mark missing token would run before
- // mark trusted creator token present.
- mExtras.enableTokenVerification();
- }
- }
-
- /** @hide */
- public void forEachNestedCreatorToken(Consumer<? super Intent> action) {
- if (mExtras == null && mClipData == null) return;
-
- if (mCreatorTokenInfo != null && mCreatorTokenInfo.mNestedIntentKeys != null) {
- int N = mCreatorTokenInfo.mNestedIntentKeys.size();
- for (int i = 0; i < N; i++) {
- NestedIntentKey key = mCreatorTokenInfo.mNestedIntentKeys.valueAt(i);
- Intent extraIntent = extractIntentFromKey(key);
-
- if (extraIntent != null) {
- action.accept(extraIntent);
- extraIntent.forEachNestedCreatorToken(action);
- } else {
- Log.w(TAG, getLogMessageForKey(key));
- }
- }
- }
- }
-
- private Intent extractIntentFromKey(NestedIntentKey key) {
- switch (key.mType) {
- case NestedIntentKey.NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL:
- return mExtras == null ? null : mExtras.getParcelable(key.mKey, Intent.class);
- case NestedIntentKey.NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_ARRAY:
- if (mExtras == null) return null;
- Intent[] extraIntents = mExtras.getParcelableArray(key.mKey, Intent.class);
- if (extraIntents != null && key.mIndex < extraIntents.length) {
- return extraIntents[key.mIndex];
- }
- break;
- case NestedIntentKey.NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_LIST:
- if (mExtras == null) return null;
- ArrayList<Intent> extraIntentsList = mExtras.getParcelableArrayList(key.mKey,
- Intent.class);
- if (extraIntentsList != null && key.mIndex < extraIntentsList.size()) {
- return extraIntentsList.get(key.mIndex);
- }
- break;
- case NestedIntentKey.NESTED_INTENT_KEY_TYPE_CLIP_DATA:
- if (mClipData == null) return null;
- if (key.mIndex < mClipData.getItemCount()) {
- ClipData.Item item = mClipData.getItemAt(key.mIndex);
- if (item != null) {
- return item.mIntent;
+ if (mExtras == null) return;
+ if (mCreatorTokenInfo != null && mCreatorTokenInfo.mExtraIntentKeys != null) {
+ for (String key : mCreatorTokenInfo.mExtraIntentKeys) {
+ try {
+ Intent extraIntent = mExtras.getParcelable(key, Intent.class);
+ if (extraIntent == null) {
+ Log.w(TAG, "The key {" + key
+ + "} does not correspond to an intent in the bundle.");
+ continue;
}
+ extraIntent.mLocalFlags |= LOCAL_FLAG_TRUSTED_CREATOR_TOKEN_PRESENT;
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to validate creator token. key: " + key + ".", e);
}
- break;
- }
- return null;
- }
-
- private String getLogMessageForKey(NestedIntentKey key) {
- switch (key.mType) {
- case NestedIntentKey.NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL:
- return "The key {" + key + "} does not correspond to an intent in the bundle.";
- case NestedIntentKey.NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_ARRAY:
- if (mExtras.getParcelableArray(key.mKey, Intent.class) == null) {
- return "The key {" + key
- + "} does not correspond to a Parcelable[] in the bundle.";
- } else {
- return "Parcelable[" + key.mIndex + "] for key {" + key + "} is not an intent.";
- }
- case NestedIntentKey.NESTED_INTENT_KEY_TYPE_EXTRA_PARCEL_LIST:
- if (mExtras.getParcelableArrayList(key.mKey, Intent.class) == null) {
- return "The key {" + key
- + "} does not correspond to an ArrayList<Parcelable> in the bundle.";
- } else {
- return "List.get(" + key.mIndex + ") for key {" + key + "} is not an intent.";
- }
- case NestedIntentKey.NESTED_INTENT_KEY_TYPE_CLIP_DATA:
- if (key.mIndex >= mClipData.getItemCount()) {
- return "Index out of range for clipData items. index: " + key.mIndex
- + ". item counts: " + mClipData.getItemCount();
- } else {
- return "clipData items at index [" + key.mIndex
- + "] is null or does not contain an intent.";
- }
- default:
- return "Unknown key type: " + key.mType;
+ }
}
+ // mark the bundle as intent extras after calls to getParcelable.
+ // otherwise, the logic to mark missing token would run before
+ // mark trusted creator token present.
+ mExtras.setIsIntentExtra();
}
/**
@@ -12560,19 +12357,7 @@ public class Intent implements Parcelable, Cloneable {
} else {
out.writeInt(1);
out.writeStrongBinder(mCreatorTokenInfo.mCreatorToken);
-
- if (mCreatorTokenInfo.mNestedIntentKeys != null) {
- final int N = mCreatorTokenInfo.mNestedIntentKeys.size();
- out.writeInt(N);
- for (int i = 0; i < N; i++) {
- NestedIntentKey key = mCreatorTokenInfo.mNestedIntentKeys.valueAt(i);
- out.writeInt(key.mType);
- out.writeString8(key.mKey);
- out.writeInt(key.mIndex);
- }
- } else {
- out.writeInt(0);
- }
+ out.writeArraySet(mCreatorTokenInfo.mExtraIntentKeys);
}
}
}
@@ -12637,18 +12422,7 @@ public class Intent implements Parcelable, Cloneable {
if (in.readInt() != 0) {
mCreatorTokenInfo = new CreatorTokenInfo();
mCreatorTokenInfo.mCreatorToken = in.readStrongBinder();
-
- N = in.readInt();
- if (N > 0) {
- mCreatorTokenInfo.mNestedIntentKeys = new ArraySet<>(N);
- for (int i = 0; i < N; i++) {
- int type = in.readInt();
- String key = in.readString8();
- int index = in.readInt();
- mCreatorTokenInfo.mNestedIntentKeys.append(
- new NestedIntentKey(type, key, index));
- }
- }
+ mCreatorTokenInfo.mExtraIntentKeys = (ArraySet<String>) in.readArraySet(null);
}
}
}
diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java
index 987e2ad768b0..2f6c6a3b02d8 100644
--- a/core/java/android/hardware/camera2/CameraMetadata.java
+++ b/core/java/android/hardware/camera2/CameraMetadata.java
@@ -3371,6 +3371,32 @@ public abstract class CameraMetadata<TKey> {
public static final int CONTROL_AUTOFRAMING_AUTO = 2;
//
+ // Enumeration values for CaptureRequest#CONTROL_ZOOM_METHOD
+ //
+
+ /**
+ * <p>The camera device automatically detects whether the application does zoom with
+ * {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} or {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}, and in turn decides which
+ * metadata tag reflects the effective zoom level.</p>
+ *
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
+ * @see CaptureRequest#SCALER_CROP_REGION
+ * @see CaptureRequest#CONTROL_ZOOM_METHOD
+ */
+ @FlaggedApi(Flags.FLAG_ZOOM_METHOD)
+ public static final int CONTROL_ZOOM_METHOD_AUTO = 0;
+
+ /**
+ * <p>The application intends to control zoom via {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}, and
+ * the effective zoom level is reflected by {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} in capture results.</p>
+ *
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
+ * @see CaptureRequest#CONTROL_ZOOM_METHOD
+ */
+ @FlaggedApi(Flags.FLAG_ZOOM_METHOD)
+ public static final int CONTROL_ZOOM_METHOD_ZOOM_RATIO = 1;
+
+ //
// Enumeration values for CaptureRequest#EDGE_MODE
//
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index 8142bbe9b838..9846cac55212 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -21,7 +21,6 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.compat.annotation.UnsupportedAppUsage;
import android.hardware.camera2.impl.CameraMetadataNative;
-import android.hardware.camera2.impl.ExtensionKey;
import android.hardware.camera2.impl.PublicKey;
import android.hardware.camera2.impl.SyntheticKey;
import android.hardware.camera2.params.OutputConfiguration;
@@ -2668,6 +2667,45 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
new Key<Integer>("android.control.autoframing", int.class);
/**
+ * <p>Whether the application uses {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} or {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}
+ * to control zoom levels.</p>
+ * <p>If set to AUTO, the camera device detects which capture request key the application uses
+ * to do zoom, {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} or {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}. If
+ * the application doesn't set android.scaler.zoomRatio or sets it to 1.0 in the capture
+ * request, the effective zoom level is reflected in {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} in capture
+ * results. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} is set to values other than 1.0, the effective
+ * zoom level is reflected in {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}. AUTO is the default value
+ * for this control, and also the behavior of the OS before Android version
+ * {@link android.os.Build.VERSION_CODES#BAKLAVA BAKLAVA}.</p>
+ * <p>If set to ZOOM_RATIO, the application explicitly specifies zoom level be controlled
+ * by {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}, and the effective zoom level is reflected in
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} in capture results. This addresses an ambiguity with AUTO,
+ * with which the camera device cannot know if the application is using cropRegion or
+ * zoomRatio at 1.0x.</p>
+ * <p><b>Possible values:</b></p>
+ * <ul>
+ * <li>{@link #CONTROL_ZOOM_METHOD_AUTO AUTO}</li>
+ * <li>{@link #CONTROL_ZOOM_METHOD_ZOOM_RATIO ZOOM_RATIO}</li>
+ * </ul>
+ *
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ * <p><b>Limited capability</b> -
+ * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
+ * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
+ *
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
+ * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
+ * @see CaptureRequest#SCALER_CROP_REGION
+ * @see #CONTROL_ZOOM_METHOD_AUTO
+ * @see #CONTROL_ZOOM_METHOD_ZOOM_RATIO
+ */
+ @PublicKey
+ @NonNull
+ @FlaggedApi(Flags.FLAG_ZOOM_METHOD)
+ public static final Key<Integer> CONTROL_ZOOM_METHOD =
+ new Key<Integer>("android.control.zoomMethod", int.class);
+
+ /**
* <p>Operation mode for edge
* enhancement.</p>
* <p>Edge enhancement improves sharpness and details in the captured image. OFF means
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index bf3a072ff097..674fc662aeac 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -22,7 +22,6 @@ import android.annotation.Nullable;
import android.compat.annotation.UnsupportedAppUsage;
import android.hardware.camera2.impl.CameraMetadataNative;
import android.hardware.camera2.impl.CaptureResultExtras;
-import android.hardware.camera2.impl.ExtensionKey;
import android.hardware.camera2.impl.PublicKey;
import android.hardware.camera2.impl.SyntheticKey;
import android.hardware.camera2.utils.TypeReference;
@@ -2915,6 +2914,45 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
new Key<Integer>("android.control.lowLightBoostState", int.class);
/**
+ * <p>Whether the application uses {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} or {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}
+ * to control zoom levels.</p>
+ * <p>If set to AUTO, the camera device detects which capture request key the application uses
+ * to do zoom, {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} or {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}. If
+ * the application doesn't set android.scaler.zoomRatio or sets it to 1.0 in the capture
+ * request, the effective zoom level is reflected in {@link CaptureRequest#SCALER_CROP_REGION android.scaler.cropRegion} in capture
+ * results. If {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} is set to values other than 1.0, the effective
+ * zoom level is reflected in {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}. AUTO is the default value
+ * for this control, and also the behavior of the OS before Android version
+ * {@link android.os.Build.VERSION_CODES#BAKLAVA BAKLAVA}.</p>
+ * <p>If set to ZOOM_RATIO, the application explicitly specifies zoom level be controlled
+ * by {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio}, and the effective zoom level is reflected in
+ * {@link CaptureRequest#CONTROL_ZOOM_RATIO android.control.zoomRatio} in capture results. This addresses an ambiguity with AUTO,
+ * with which the camera device cannot know if the application is using cropRegion or
+ * zoomRatio at 1.0x.</p>
+ * <p><b>Possible values:</b></p>
+ * <ul>
+ * <li>{@link #CONTROL_ZOOM_METHOD_AUTO AUTO}</li>
+ * <li>{@link #CONTROL_ZOOM_METHOD_ZOOM_RATIO ZOOM_RATIO}</li>
+ * </ul>
+ *
+ * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
+ * <p><b>Limited capability</b> -
+ * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
+ * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
+ *
+ * @see CaptureRequest#CONTROL_ZOOM_RATIO
+ * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
+ * @see CaptureRequest#SCALER_CROP_REGION
+ * @see #CONTROL_ZOOM_METHOD_AUTO
+ * @see #CONTROL_ZOOM_METHOD_ZOOM_RATIO
+ */
+ @PublicKey
+ @NonNull
+ @FlaggedApi(Flags.FLAG_ZOOM_METHOD)
+ public static final Key<Integer> CONTROL_ZOOM_METHOD =
+ new Key<Integer>("android.control.zoomMethod", int.class);
+
+ /**
* <p>Operation mode for edge
* enhancement.</p>
* <p>Edge enhancement improves sharpness and details in the captured image. OFF means
diff --git a/core/java/android/hardware/input/KeyGestureEvent.java b/core/java/android/hardware/input/KeyGestureEvent.java
index 9d42b67bf5a8..506a19cce159 100644
--- a/core/java/android/hardware/input/KeyGestureEvent.java
+++ b/core/java/android/hardware/input/KeyGestureEvent.java
@@ -117,6 +117,8 @@ public final class KeyGestureEvent {
public static final int KEY_GESTURE_TYPE_SNAP_RIGHT_FREEFORM_WINDOW = 69;
public static final int KEY_GESTURE_TYPE_MAXIMIZE_FREEFORM_WINDOW = 70;
public static final int KEY_GESTURE_TYPE_RESTORE_FREEFORM_WINDOW_SIZE = 71;
+ public static final int KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_IN = 72;
+ public static final int KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_OUT = 73;
public static final int FLAG_CANCELLED = 1;
@@ -203,6 +205,8 @@ public final class KeyGestureEvent {
KEY_GESTURE_TYPE_SNAP_RIGHT_FREEFORM_WINDOW,
KEY_GESTURE_TYPE_MAXIMIZE_FREEFORM_WINDOW,
KEY_GESTURE_TYPE_RESTORE_FREEFORM_WINDOW_SIZE,
+ KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_IN,
+ KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_OUT,
})
@Retention(RetentionPolicy.SOURCE)
public @interface KeyGestureType {
@@ -773,6 +777,10 @@ public final class KeyGestureEvent {
return "KEY_GESTURE_TYPE_SNAP_RIGHT_FREEFORM_WINDOW";
case KEY_GESTURE_TYPE_RESTORE_FREEFORM_WINDOW_SIZE:
return "KEY_GESTURE_TYPE_RESTORE_FREEFORM_WINDOW_SIZE";
+ case KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_IN:
+ return "KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_IN";
+ case KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_OUT:
+ return "KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_OUT";
default:
return Integer.toHexString(value);
}
diff --git a/core/java/android/hardware/input/input_framework.aconfig b/core/java/android/hardware/input/input_framework.aconfig
index 38e32c61c99e..a8eb11d88aa4 100644
--- a/core/java/android/hardware/input/input_framework.aconfig
+++ b/core/java/android/hardware/input/input_framework.aconfig
@@ -30,14 +30,6 @@ flag {
flag {
namespace: "input_native"
- name: "emoji_and_screenshot_keycodes_available"
- is_exported: true
- description: "Add new KeyEvent keycodes for opening Emoji Picker and Taking Screenshots"
- bug: "315307777"
-}
-
-flag {
- namespace: "input_native"
name: "keyboard_a11y_slow_keys_flag"
description: "Controls if the slow keys accessibility feature for physical keyboard is available to the user"
bug: "294546335"
@@ -153,6 +145,13 @@ flag {
}
flag {
+ name: "enable_new_25q2_keycodes"
+ namespace: "input"
+ description: "Enables new 25Q2 keycodes"
+ bug: "365920375"
+}
+
+flag {
name: "override_power_key_behavior_in_focused_window"
namespace: "input_native"
description: "Allows privileged focused windows to capture power key events."
diff --git a/core/java/android/os/Bundle.java b/core/java/android/os/Bundle.java
index 99e7d166446e..c18fb0c38b82 100644
--- a/core/java/android/os/Bundle.java
+++ b/core/java/android/os/Bundle.java
@@ -281,7 +281,7 @@ public final class Bundle extends BaseBundle implements Cloneable, Parcelable {
}
/** {@hide} */
- public void enableTokenVerification() {
+ public void setIsIntentExtra() {
mFlags |= FLAG_VERIFY_TOKENS_PRESENT;
}
diff --git a/core/java/android/os/flags.aconfig b/core/java/android/os/flags.aconfig
index 9c83bc2c88ec..d9db28e0b3c3 100644
--- a/core/java/android/os/flags.aconfig
+++ b/core/java/android/os/flags.aconfig
@@ -243,6 +243,15 @@ flag {
}
flag {
+ name: "update_engine_api"
+ namespace: "art_mainline"
+ description: "Update Engine APIs for ART"
+ is_exported: true
+ is_fixed_read_only: true
+ bug: "377557749"
+}
+
+flag {
namespace: "system_performance"
name: "perfetto_sdk_tracing"
description: "Tracing using Perfetto SDK."
diff --git a/core/java/android/permission/flags.aconfig b/core/java/android/permission/flags.aconfig
index 9e0d0e195a96..60a0ae3f107d 100644
--- a/core/java/android/permission/flags.aconfig
+++ b/core/java/android/permission/flags.aconfig
@@ -354,9 +354,10 @@ flag {
flag {
name: "health_connect_backup_restore_permission_enabled"
is_fixed_read_only: true
- namespace: "health_connect"
+ namespace: "health_fitness_aconfig"
description: "This flag protects the permission that is required to call Health Connect backup and restore apis"
bug: "376014879" # android_fr bug
+ is_exported: true
}
flag {
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index d19681c86320..ef351719ea70 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -8687,6 +8687,19 @@ public final class Settings {
public static final String ACCESSIBILITY_QS_TARGETS = "accessibility_qs_targets";
/**
+ * Setting specifying the accessibility services, accessibility shortcut targets,
+ * or features to be toggled via a keyboard shortcut gesture.
+ *
+ * <p> This is a colon-separated string list which contains the flattened
+ * {@link ComponentName} and the class name of a system class implementing a supported
+ * accessibility feature.
+ *
+ * @hide
+ */
+ public static final String ACCESSIBILITY_KEY_GESTURE_TARGETS =
+ "accessibility_key_gesture_targets";
+
+ /**
* The system class name of magnification controller which is a target to be toggled via
* accessibility shortcut or accessibility button.
*
diff --git a/core/java/android/security/flags.aconfig b/core/java/android/security/flags.aconfig
index 1d35344e5218..7cb0ffcfcc72 100644
--- a/core/java/android/security/flags.aconfig
+++ b/core/java/android/security/flags.aconfig
@@ -120,3 +120,10 @@ flag {
description: "Feature flag for exposing KeyStore grant APIs"
bug: "351158708"
}
+
+flag {
+ name: "secure_lockdown"
+ namespace: "biometrics"
+ description: "Feature flag for Secure Lockdown feature"
+ bug: "373422357"
+} \ No newline at end of file
diff --git a/core/java/android/service/settings/preferences/ISettingsPreferenceService.aidl b/core/java/android/service/settings/preferences/ISettingsPreferenceService.aidl
new file mode 100644
index 000000000000..64a8b90fe581
--- /dev/null
+++ b/core/java/android/service/settings/preferences/ISettingsPreferenceService.aidl
@@ -0,0 +1,18 @@
+package android.service.settings.preferences;
+
+import android.service.settings.preferences.GetValueRequest;
+import android.service.settings.preferences.IGetValueCallback;
+import android.service.settings.preferences.IMetadataCallback;
+import android.service.settings.preferences.ISetValueCallback;
+import android.service.settings.preferences.MetadataRequest;
+import android.service.settings.preferences.SetValueRequest;
+
+/** @hide */
+oneway interface ISettingsPreferenceService {
+ @EnforcePermission("READ_SYSTEM_PREFERENCES")
+ void getAllPreferenceMetadata(in MetadataRequest request, IMetadataCallback callback) = 1;
+ @EnforcePermission("READ_SYSTEM_PREFERENCES")
+ void getPreferenceValue(in GetValueRequest request, IGetValueCallback callback) = 2;
+ @EnforcePermission(allOf = {"READ_SYSTEM_PREFERENCES", "WRITE_SYSTEM_PREFERENCES"})
+ void setPreferenceValue(in SetValueRequest request, ISetValueCallback callback) = 3;
+}
diff --git a/core/java/android/service/settings/preferences/SettingsPreferenceService.java b/core/java/android/service/settings/preferences/SettingsPreferenceService.java
new file mode 100644
index 000000000000..4a4b5d201f09
--- /dev/null
+++ b/core/java/android/service/settings/preferences/SettingsPreferenceService.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2024 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.service.settings.preferences;
+
+import android.Manifest;
+import android.annotation.EnforcePermission;
+import android.annotation.FlaggedApi;
+import android.app.Service;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.os.IBinder;
+import android.os.OutcomeReceiver;
+import android.os.PermissionEnforcer;
+import android.os.RemoteException;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import com.android.settingslib.flags.Flags;
+
+/**
+ * Base class for a service that exposes its settings preferences to external access.
+ * <p>This class is to be implemented by apps that contribute to the Android Settings surface.
+ * Access to this service is permission guarded by
+ * {@link android.permission.READ_SYSTEM_PREFERENCES} for binding and reading, and guarded by both
+ * {@link android.permission.READ_SYSTEM_PREFERENCES} and
+ * {@link android.permission.WRITE_SYSTEM_PREFERENCES} for writing. An additional checks for access
+ * control are the responsibility of the implementing class.
+ *
+ * <p>This implementation must correspond to an exported service declaration in the host app
+ * AndroidManifest.xml as follows
+ * <pre class="prettyprint">
+ * {@literal
+ * <service
+ * android:permission="android.permission.READ_SYSTEM_PREFERENCES"
+ * android:exported="true">
+ * <intent-filter>
+ * <action android:name="android.service.settings.preferences.action.PREFERENCE_SERVICE" />
+ * </intent-filter>
+ * </service>}
+ * </pre>
+ *
+ * <ul>
+ * <li>It is recommended to expose the metadata for most, if not all, preferences within a
+ * settings app, thus implementing {@link #onGetAllPreferenceMetadata}.
+ * <li>Exposing preferences for read access of their values is up to the implementer, but any
+ * exposed must be a subset of the preferences exposed in {@link #onGetAllPreferenceMetadata}.
+ * To expose a preference for read access, the implementation will contain
+ * {@link #onGetPreferenceValue}.
+ * <li>Exposing a preference for write access of their values is up to the implementer, but should
+ * be done so with extra care and consideration, both for security and privacy. These must also
+ * be a subset of those exposed in {@link #onGetAllPreferenceMetadata}. To expose a preference for
+ * write access, the implementation will contain {@link #onSetPreferenceValue}.
+ * </ul>
+ */
+@FlaggedApi(Flags.FLAG_SETTINGS_CATALYST)
+public abstract class SettingsPreferenceService extends Service {
+
+ /**
+ * Intent Action corresponding to a {@link SettingsPreferenceService}. Note that any checks for
+ * such services must be accompanied by a check to ensure the host is a system application.
+ * Given an {@link android.content.pm.ApplicationInfo} you can check for
+ * {@link android.content.pm.ApplicationInfo#FLAG_SYSTEM}, or when querying
+ * {@link PackageManager#queryIntentServices} you can provide the flag
+ * {@link PackageManager#MATCH_SYSTEM_ONLY}.
+ */
+ public static final String ACTION_PREFERENCE_SERVICE =
+ "android.service.settings.preferences.action.PREFERENCE_SERVICE";
+
+ /** @hide */
+ @NonNull
+ @Override
+ public final IBinder onBind(@Nullable Intent intent) {
+ return new ISettingsPreferenceService.Stub(
+ PermissionEnforcer.fromContext(getApplicationContext())) {
+ @EnforcePermission(Manifest.permission.READ_SYSTEM_PREFERENCES)
+ @Override
+ public void getAllPreferenceMetadata(MetadataRequest request,
+ IMetadataCallback callback) {
+ getAllPreferenceMetadata_enforcePermission();
+ onGetAllPreferenceMetadata(request, new OutcomeReceiver<>() {
+ @Override
+ public void onResult(MetadataResult result) {
+ try {
+ callback.onSuccess(result);
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+
+ @Override
+ public void onError(@NonNull Exception error) {
+ try {
+ callback.onFailure();
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+ });
+ }
+
+ @EnforcePermission(Manifest.permission.READ_SYSTEM_PREFERENCES)
+ @Override
+ public void getPreferenceValue(GetValueRequest request, IGetValueCallback callback) {
+ getPreferenceValue_enforcePermission();
+ onGetPreferenceValue(request, new OutcomeReceiver<>() {
+ @Override
+ public void onResult(GetValueResult result) {
+ try {
+ callback.onSuccess(result);
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+
+ @Override
+ public void onError(@NonNull Exception error) {
+ try {
+ callback.onFailure();
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+ });
+ }
+
+ @EnforcePermission(allOf = {
+ Manifest.permission.READ_SYSTEM_PREFERENCES,
+ Manifest.permission.WRITE_SYSTEM_PREFERENCES
+ })
+ @Override
+ public void setPreferenceValue(SetValueRequest request, ISetValueCallback callback) {
+ setPreferenceValue_enforcePermission();
+ onSetPreferenceValue(request, new OutcomeReceiver<>() {
+ @Override
+ public void onResult(SetValueResult result) {
+ try {
+ callback.onSuccess(result);
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+
+ @Override
+ public void onError(@NonNull Exception error) {
+ try {
+ callback.onFailure();
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+ });
+ }
+ };
+ }
+
+ /**
+ * Retrieve the metadata for all exposed settings preferences within this application. This
+ * data should be a snapshot of their state at the time of this method being called.
+ * @param request object to specify request parameters
+ * @param callback object to receive result or failure of request
+ */
+ public abstract void onGetAllPreferenceMetadata(
+ @NonNull MetadataRequest request,
+ @NonNull OutcomeReceiver<MetadataResult, Exception> callback);
+
+ /**
+ * Retrieve the current value of the requested settings preference. If this value is not exposed
+ * or cannot be obtained for some reason, the corresponding result code will be set on the
+ * result object.
+ * @param request object to specify request parameters
+ * @param callback object to receive result or failure of request
+ */
+ public abstract void onGetPreferenceValue(
+ @NonNull GetValueRequest request,
+ @NonNull OutcomeReceiver<GetValueResult, Exception> callback);
+
+ /**
+ * Set the value within the request to the target settings preference. If this value cannot
+ * be written for some reason, the corresponding result code will be set on the result object.
+ * @param request object to specify request parameters
+ * @param callback object to receive result or failure of request
+ */
+ public abstract void onSetPreferenceValue(
+ @NonNull SetValueRequest request,
+ @NonNull OutcomeReceiver<SetValueResult, Exception> callback);
+}
diff --git a/core/java/android/service/settings/preferences/SettingsPreferenceServiceClient.java b/core/java/android/service/settings/preferences/SettingsPreferenceServiceClient.java
new file mode 100644
index 000000000000..39995a47fcbe
--- /dev/null
+++ b/core/java/android/service/settings/preferences/SettingsPreferenceServiceClient.java
@@ -0,0 +1,248 @@
+/*
+ * Copyright (C) 2024 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.service.settings.preferences;
+
+import static android.service.settings.preferences.SettingsPreferenceService.ACTION_PREFERENCE_SERVICE;
+
+import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
+import android.annotation.TestApi;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.os.IBinder;
+import android.os.OutcomeReceiver;
+import android.os.RemoteException;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import com.android.settingslib.flags.Flags;
+
+import java.util.List;
+import java.util.concurrent.Executor;
+
+/**
+ * Client class responsible for binding to and interacting with an instance of
+ * {@link SettingsPreferenceService}.
+ * <p>This is a convenience class to handle the lifecycle of the service connection.
+ * <p>This client will only interact with one instance at a time,
+ * so if the caller requires multiple instances (multiple applications that provide settings), then
+ * the caller must create multiple client classes, one for each instance required. To find all
+ * available services, a caller may query {@link android.content.pm.PackageManager} for applications
+ * that provide the intent action {@link SettingsPreferenceService#ACTION_PREFERENCE_SERVICE} that
+ * are also system applications ({@link android.content.pm.ApplicationInfo#FLAG_SYSTEM}).
+ */
+@FlaggedApi(Flags.FLAG_SETTINGS_CATALYST)
+public class SettingsPreferenceServiceClient implements AutoCloseable {
+
+ private final Context mContext;
+ private final Intent mServiceIntent;
+ private final ServiceConnection mServiceConnection;
+ private final boolean mSystemOnly;
+ private ISettingsPreferenceService mRemoteService;
+
+ /**
+ * Construct a client for binding to a {@link SettingsPreferenceService} provided by the
+ * application corresponding to the provided package name.
+ * @param packageName - package name for which this client will initiate a service binding
+ */
+ public SettingsPreferenceServiceClient(@NonNull Context context,
+ @NonNull String packageName) {
+ this(context, packageName, true, null);
+ }
+
+ /**
+ * @hide Only to be called directly by test
+ */
+ @TestApi
+ public SettingsPreferenceServiceClient(@NonNull Context context,
+ @NonNull String packageName,
+ boolean systemOnly,
+ @Nullable ServiceConnection connectionListener) {
+ mContext = context.getApplicationContext();
+ mServiceIntent = new Intent(ACTION_PREFERENCE_SERVICE).setPackage(packageName);
+ mSystemOnly = systemOnly;
+ mServiceConnection = createServiceConnection(connectionListener);
+ }
+
+ /**
+ * Initiate binding to service.
+ * <p>If no service exists for the package provided or the package is not for a system
+ * application, no binding will occur.
+ */
+ public void start() {
+ PackageManager pm = mContext.getPackageManager();
+ PackageManager.ResolveInfoFlags flags;
+ if (mSystemOnly) {
+ flags = PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_SYSTEM_ONLY);
+ } else {
+ flags = PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_ALL);
+ }
+ List<ResolveInfo> infos = pm.queryIntentServices(mServiceIntent, flags);
+ if (infos.size() == 1) {
+ mContext.bindService(mServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
+ }
+ }
+
+ /**
+ * If there is an active service binding, unbind from that service.
+ */
+ public void stop() {
+ if (mRemoteService != null) {
+ mRemoteService = null;
+ mContext.unbindService(mServiceConnection);
+ }
+ }
+
+ /**
+ * Retrieve the metadata for all exposed settings preferences within the application.
+ * @param request object to specify request parameters
+ * @param executor {@link Executor} on which to invoke the receiver
+ * @param receiver callback to receive the result or failure
+ */
+ public void getAllPreferenceMetadata(
+ @NonNull MetadataRequest request,
+ @CallbackExecutor @NonNull Executor executor,
+ @NonNull OutcomeReceiver<MetadataResult, Exception> receiver) {
+ if (mRemoteService == null) {
+ executor.execute(() ->
+ receiver.onError(new IllegalStateException("Service not ready")));
+ return;
+ }
+ try {
+ mRemoteService.getAllPreferenceMetadata(request, new IMetadataCallback.Stub() {
+ @Override
+ public void onSuccess(MetadataResult result) {
+ executor.execute(() -> receiver.onResult(result));
+ }
+
+ @Override
+ public void onFailure() {
+ executor.execute(() -> receiver.onError(
+ new IllegalStateException("Service call failure")));
+ }
+ });
+ } catch (RemoteException | RuntimeException e) {
+ executor.execute(() -> receiver.onError(e));
+ }
+ }
+
+ /**
+ * Retrieve the current value of the requested settings preference.
+ * @param request object to specify request parameters
+ * @param executor {@link Executor} on which to invoke the receiver
+ * @param receiver callback to receive the result or failure
+ */
+ public void getPreferenceValue(@NonNull GetValueRequest request,
+ @CallbackExecutor @NonNull Executor executor,
+ @NonNull OutcomeReceiver<GetValueResult, Exception> receiver) {
+ if (mRemoteService == null) {
+ executor.execute(() ->
+ receiver.onError(new IllegalStateException("Service not ready")));
+ return;
+ }
+ try {
+ mRemoteService.getPreferenceValue(request, new IGetValueCallback.Stub() {
+ @Override
+ public void onSuccess(GetValueResult result) {
+ executor.execute(() -> receiver.onResult(result));
+ }
+
+ @Override
+ public void onFailure() {
+ executor.execute(() -> receiver.onError(
+ new IllegalStateException("Service call failure")));
+ }
+ });
+ } catch (RemoteException | RuntimeException e) {
+ executor.execute(() -> receiver.onError(e));
+ }
+ }
+
+ /**
+ * Set the value on the target settings preference.
+ * @param request object to specify request parameters
+ * @param executor {@link Executor} on which to invoke the receiver
+ * @param receiver callback to receive the result or failure
+ */
+ public void setPreferenceValue(@NonNull SetValueRequest request,
+ @CallbackExecutor @NonNull Executor executor,
+ @NonNull OutcomeReceiver<SetValueResult, Exception> receiver) {
+ if (mRemoteService == null) {
+ executor.execute(() ->
+ receiver.onError(new IllegalStateException("Service not ready")));
+ return;
+ }
+ try {
+ mRemoteService.setPreferenceValue(request, new ISetValueCallback.Stub() {
+ @Override
+ public void onSuccess(SetValueResult result) {
+ executor.execute(() -> receiver.onResult(result));
+ }
+
+ @Override
+ public void onFailure() {
+ executor.execute(() -> receiver.onError(
+ new IllegalStateException("Service call failure")));
+ }
+ });
+ } catch (RemoteException | RuntimeException e) {
+ executor.execute(() -> receiver.onError(e));
+ }
+ }
+
+ @NonNull
+ private ServiceConnection createServiceConnection(@Nullable ServiceConnection listener) {
+ return new ServiceConnection() {
+ @Override
+ public void onServiceConnected(ComponentName name, IBinder service) {
+ mRemoteService = getPreferenceServiceInterface(service);
+ if (listener != null) {
+ listener.onServiceConnected(name, service);
+ }
+ }
+
+ @Override
+ public void onServiceDisconnected(ComponentName name) {
+ mRemoteService = null;
+ if (listener != null) {
+ listener.onServiceDisconnected(name);
+ }
+ }
+ };
+ }
+
+ @NonNull
+ private ISettingsPreferenceService getPreferenceServiceInterface(@NonNull IBinder service) {
+ return ISettingsPreferenceService.Stub.asInterface(service);
+ }
+
+ /**
+ * This client handles a resource, thus is it important to appropriately close that resource
+ * when it is no longer needed.
+ * <p>This method is provided by {@link AutoCloseable} and calling it
+ * will unbind any service binding.
+ */
+ @Override
+ public void close() {
+ stop();
+ }
+}
diff --git a/core/java/android/telephony/PhoneStateListener.java b/core/java/android/telephony/PhoneStateListener.java
index bce51f297aff..1df3b4332754 100644
--- a/core/java/android/telephony/PhoneStateListener.java
+++ b/core/java/android/telephony/PhoneStateListener.java
@@ -37,6 +37,7 @@ import android.telephony.TelephonyManager.EmergencyCallbackModeType;
import android.telephony.emergency.EmergencyNumber;
import android.telephony.ims.ImsReasonInfo;
import android.telephony.ims.MediaQualityStatus;
+import android.telephony.satellite.NtnSignalStrength;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.telephony.IPhoneStateListener;
@@ -1706,6 +1707,11 @@ public class PhoneStateListener {
@NetworkRegistrationInfo.ServiceType int[] availableServices) {
// not supported on the deprecated interface - Use TelephonyCallback instead
}
+
+ public final void onCarrierRoamingNtnSignalStrengthChanged(
+ @NonNull NtnSignalStrength ntnSignalStrength) {
+ // not supported on the deprecated interface - Use TelephonyCallback instead
+ }
}
private void log(String s) {
diff --git a/core/java/android/telephony/TelephonyCallback.java b/core/java/android/telephony/TelephonyCallback.java
index 64a5533cbe69..0d1dc4611343 100644
--- a/core/java/android/telephony/TelephonyCallback.java
+++ b/core/java/android/telephony/TelephonyCallback.java
@@ -30,6 +30,7 @@ import android.telephony.emergency.EmergencyNumber;
import android.telephony.ims.ImsReasonInfo;
import android.telephony.ims.MediaQualityStatus;
import android.telephony.ims.MediaThreshold;
+import android.telephony.satellite.NtnSignalStrength;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
@@ -695,6 +696,15 @@ public class TelephonyCallback {
public static final int EVENT_CARRIER_ROAMING_NTN_AVAILABLE_SERVICES_CHANGED = 44;
/**
+ * Event for listening to carrier roaming non-terrestrial network signal strength changes.
+ *
+ * @see CarrierRoamingNtnModeListener
+ *
+ * @hide
+ */
+ public static final int EVENT_CARRIER_ROAMING_NTN_SIGNAL_STRENGTH_CHANGED = 45;
+
+ /**
* @hide
*/
@IntDef(prefix = {"EVENT_"}, value = {
@@ -741,7 +751,8 @@ public class TelephonyCallback {
EVENT_SIMULTANEOUS_CELLULAR_CALLING_SUBSCRIPTIONS_CHANGED,
EVENT_CARRIER_ROAMING_NTN_MODE_CHANGED,
EVENT_CARRIER_ROAMING_NTN_ELIGIBLE_STATE_CHANGED,
- EVENT_CARRIER_ROAMING_NTN_AVAILABLE_SERVICES_CHANGED
+ EVENT_CARRIER_ROAMING_NTN_AVAILABLE_SERVICES_CHANGED,
+ EVENT_CARRIER_ROAMING_NTN_SIGNAL_STRENGTH_CHANGED
})
@Retention(RetentionPolicy.SOURCE)
public @interface TelephonyEvent {
@@ -1805,6 +1816,14 @@ public class TelephonyCallback {
*/
default void onCarrierRoamingNtnAvailableServicesChanged(
@NetworkRegistrationInfo.ServiceType List<Integer> availableServices) {}
+
+ /**
+ * Callback invoked when carrier roaming non-terrestrial network signal strength changes.
+ *
+ * @param ntnSignalStrength non-terrestrial network signal strength.
+ */
+ default void onCarrierRoamingNtnSignalStrengthChanged(
+ @NonNull NtnSignalStrength ntnSignalStrength) {}
}
/**
@@ -2270,5 +2289,18 @@ public class TelephonyCallback {
Binder.withCleanCallingIdentity(() -> mExecutor.execute(
() -> listener.onCarrierRoamingNtnAvailableServicesChanged(ServiceList)));
}
+
+ public void onCarrierRoamingNtnSignalStrengthChanged(
+ @NonNull NtnSignalStrength ntnSignalStrength) {
+ if (!Flags.carrierRoamingNbIotNtn()) return;
+
+ CarrierRoamingNtnModeListener listener =
+ (CarrierRoamingNtnModeListener) mTelephonyCallbackWeakRef.get();
+ if (listener == null) return;
+
+ Binder.withCleanCallingIdentity(() -> mExecutor.execute(
+ () -> listener.onCarrierRoamingNtnSignalStrengthChanged(ntnSignalStrength)));
+
+ }
}
}
diff --git a/core/java/android/telephony/TelephonyRegistryManager.java b/core/java/android/telephony/TelephonyRegistryManager.java
index 1dab2cf75594..90b0bb34c145 100644
--- a/core/java/android/telephony/TelephonyRegistryManager.java
+++ b/core/java/android/telephony/TelephonyRegistryManager.java
@@ -47,6 +47,7 @@ import android.telephony.emergency.EmergencyNumber;
import android.telephony.ims.ImsCallSession;
import android.telephony.ims.ImsReasonInfo;
import android.telephony.ims.MediaQualityStatus;
+import android.telephony.satellite.NtnSignalStrength;
import android.telephony.satellite.SatelliteStateChangeListener;
import android.util.ArrayMap;
import android.util.ArraySet;
@@ -1137,6 +1138,23 @@ public class TelephonyRegistryManager {
}
/**
+ * Notify external listeners that carrier roaming non-terrestrial network
+ * signal strength changed.
+ * @param subId subscription ID.
+ * @param ntnSignalStrength non-terrestrial network signal strength.
+ * @hide
+ */
+ public final void notifyCarrierRoamingNtnSignalStrengthChanged(int subId,
+ @NonNull NtnSignalStrength ntnSignalStrength) {
+ try {
+ sRegistry.notifyCarrierRoamingNtnSignalStrengthChanged(subId, ntnSignalStrength);
+ } catch (RemoteException ex) {
+ // system server crash
+ throw ex.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Processes potential event changes from the provided {@link TelephonyCallback}.
*
* @param telephonyCallback callback for monitoring callback changes to the telephony state.
@@ -1293,6 +1311,7 @@ public class TelephonyRegistryManager {
eventList.add(TelephonyCallback.EVENT_CARRIER_ROAMING_NTN_MODE_CHANGED);
eventList.add(TelephonyCallback.EVENT_CARRIER_ROAMING_NTN_ELIGIBLE_STATE_CHANGED);
eventList.add(TelephonyCallback.EVENT_CARRIER_ROAMING_NTN_AVAILABLE_SERVICES_CHANGED);
+ eventList.add(TelephonyCallback.EVENT_CARRIER_ROAMING_NTN_SIGNAL_STRENGTH_CHANGED);
}
return eventList;
}
diff --git a/core/java/android/view/KeyEvent.java b/core/java/android/view/KeyEvent.java
index dddc408ed9db..38e4e2760d25 100644
--- a/core/java/android/view/KeyEvent.java
+++ b/core/java/android/view/KeyEvent.java
@@ -935,7 +935,6 @@ public class KeyEvent extends InputEvent implements Parcelable {
*/
public static final int KEYCODE_MACRO_4 = 316;
/** Key code constant: To open emoji picker */
- @FlaggedApi(Flags.FLAG_EMOJI_AND_SCREENSHOT_KEYCODES_AVAILABLE)
public static final int KEYCODE_EMOJI_PICKER = 317;
/**
* Key code constant: To take a screenshot
@@ -944,15 +943,80 @@ public class KeyEvent extends InputEvent implements Parcelable {
* unlike {@code KEYCODE_SYSRQ} which is sent to the app first and only if the app
* doesn't handle it, the framework handles it (to take a screenshot).
*/
- @FlaggedApi(Flags.FLAG_EMOJI_AND_SCREENSHOT_KEYCODES_AVAILABLE)
public static final int KEYCODE_SCREENSHOT = 318;
+ /** Key code constant: To start dictate to an input field */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_DICTATE = 319;
+ /**
+ * Key code constant: AC New
+ *
+ * e.g. To create a new instance of a window, open a new tab, etc.
+ */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_NEW = 320;
+ /**
+ * Key code constant: AC Close
+ *
+ * e.g. To close current instance of the application window, close the current tab, etc.
+ */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_CLOSE = 321;
+ /** Key code constant: To toggle 'Do Not Disturb' mode */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_DO_NOT_DISTURB = 322;
+ /** Key code constant: To Print */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_PRINT = 323;
+ /** Key code constant: To Lock the screen */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_LOCK = 324;
+ /** Key code constant: To toggle fullscreen mode (on the current application) */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_FULLSCREEN = 325;
+ /** Key code constant: F13 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F13 = 326;
+ /** Key code constant: F14 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F14 = 327;
+ /** Key code constant: F15 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F15 = 328;
+ /** Key code constant: F16 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F16 = 329;
+ /** Key code constant: F17 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F17 = 330;
+ /** Key code constant: F18 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F18 = 331;
+ /** Key code constant: F19 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F19 = 332;
+ /** Key code constant: F20 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F20 = 333;
+ /** Key code constant: F21 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F21 = 334;
+ /** Key code constant: F22 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F22 = 335;
+ /** Key code constant: F23 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F23 = 336;
+ /** Key code constant: F24 key. */
+ @FlaggedApi(Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
+ public static final int KEYCODE_F24 = 337;
/**
* Integer value of the last KEYCODE. Increases as new keycodes are added to KeyEvent.
* @hide
*/
@TestApi
- public static final int LAST_KEYCODE = KEYCODE_SCREENSHOT;
+ @SuppressWarnings("FlaggedApi")
+ public static final int LAST_KEYCODE = KEYCODE_F24;
/** @hide */
@IntDef(prefix = {"KEYCODE_"}, value = {
@@ -1275,6 +1339,25 @@ public class KeyEvent extends InputEvent implements Parcelable {
KEYCODE_MACRO_4,
KEYCODE_EMOJI_PICKER,
KEYCODE_SCREENSHOT,
+ KEYCODE_DICTATE,
+ KEYCODE_NEW,
+ KEYCODE_CLOSE,
+ KEYCODE_DO_NOT_DISTURB,
+ KEYCODE_PRINT,
+ KEYCODE_LOCK,
+ KEYCODE_FULLSCREEN,
+ KEYCODE_F13,
+ KEYCODE_F14,
+ KEYCODE_F15,
+ KEYCODE_F16,
+ KEYCODE_F17,
+ KEYCODE_F18,
+ KEYCODE_F19,
+ KEYCODE_F20,
+ KEYCODE_F21,
+ KEYCODE_F22,
+ KEYCODE_F23,
+ KEYCODE_F24,
})
@Retention(RetentionPolicy.SOURCE)
@interface KeyCode {}
diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java
index df54d310059f..206c73756088 100644
--- a/core/java/android/view/SurfaceControl.java
+++ b/core/java/android/view/SurfaceControl.java
@@ -2989,7 +2989,6 @@ public final class SurfaceControl implements Parcelable {
private void apply(boolean sync, boolean oneWay) {
applyResizedSurfaces();
notifyReparentedSurfaces();
- nativeApplyTransaction(mNativeObject, sync, oneWay);
if (SurfaceControlRegistry.sCallStackDebuggingEnabled) {
SurfaceControlRegistry.getProcessInstance().checkCallStackDebugging(
@@ -2998,6 +2997,7 @@ public final class SurfaceControl implements Parcelable {
if (mCalls != null) {
mCalls.clear();
}
+ nativeApplyTransaction(mNativeObject, sync, oneWay);
}
/**
diff --git a/core/java/android/view/accessibility/AccessibilityNodeInfo.java b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
index 14652035438d..0204517e869a 100644
--- a/core/java/android/view/accessibility/AccessibilityNodeInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
@@ -3866,8 +3866,14 @@ public class AccessibilityNodeInfo implements Parcelable {
* Sets the view for which the view represented by this info serves as a
* label for accessibility purposes.
*
+ * @deprecated Use {@link #addLabeledBy(View)} on the labeled node instead,
+ * since {@link #getLabeledByList()} and {@link #getLabeledBy()} on the
+ * labeled node are not automatically populated when this method is used.
+ *
* @param labeled The view for which this info serves as a label.
*/
+ @FlaggedApi(Flags.FLAG_DEPRECATE_ANI_LABEL_FOR_APIS)
+ @Deprecated
public void setLabelFor(View labeled) {
setLabelFor(labeled, AccessibilityNodeProvider.HOST_VIEW_ID);
}
@@ -3888,9 +3894,15 @@ public class AccessibilityNodeInfo implements Parcelable {
* This class is made immutable before being delivered to an AccessibilityService.
* </p>
*
+ * @deprecated Use {@link #addLabeledBy(View)} on the labeled node instead,
+ * since {@link #getLabeledByList()} and {@link #getLabeledBy()} on the
+ * labeled node are not automatically populated when this method is used.
+ *
* @param root The root whose virtual descendant serves as a label.
* @param virtualDescendantId The id of the virtual descendant.
*/
+ @FlaggedApi(Flags.FLAG_DEPRECATE_ANI_LABEL_FOR_APIS)
+ @Deprecated
public void setLabelFor(View root, int virtualDescendantId) {
enforceNotSealed();
final int rootAccessibilityViewId = (root != null)
@@ -3902,8 +3914,14 @@ public class AccessibilityNodeInfo implements Parcelable {
* Gets the node info for which the view represented by this info serves as
* a label for accessibility purposes.
*
+ * @deprecated Use {@link #getLabeledByList()} on the labeled node instead,
+ * since calling {@link #addLabeledBy(View)} or {@link #addLabeledBy(View, int)}
+ * on the labeled node do not automatically provide that node from this method.
+ *
* @return The labeled info.
*/
+ @FlaggedApi(Flags.FLAG_DEPRECATE_ANI_LABEL_FOR_APIS)
+ @Deprecated
public AccessibilityNodeInfo getLabelFor() {
enforceSealed();
return getNodeForAccessibilityId(mConnectionId, mWindowId, mLabelForId);
diff --git a/core/java/android/view/accessibility/flags/accessibility_flags.aconfig b/core/java/android/view/accessibility/flags/accessibility_flags.aconfig
index 7177ef330f06..8a006fa5b509 100644
--- a/core/java/android/view/accessibility/flags/accessibility_flags.aconfig
+++ b/core/java/android/view/accessibility/flags/accessibility_flags.aconfig
@@ -92,6 +92,13 @@ flag {
flag {
namespace: "accessibility"
+ name: "deprecate_ani_label_for_apis"
+ description: "Controls the deprecation of AccessibilityNodeInfo labelFor apis"
+ bug: "333783827"
+}
+
+flag {
+ namespace: "accessibility"
name: "fix_merged_content_change_event_v2"
description: "Fixes event type and source of content change event merged in ViewRootImpl"
bug: "277305460"
diff --git a/core/java/android/view/autofill/AutofillFeatureFlags.java b/core/java/android/view/autofill/AutofillFeatureFlags.java
index 0ab51e45a951..905f350ca6c5 100644
--- a/core/java/android/view/autofill/AutofillFeatureFlags.java
+++ b/core/java/android/view/autofill/AutofillFeatureFlags.java
@@ -316,6 +316,35 @@ public class AutofillFeatureFlags {
// END AUTOFILL PCC CLASSIFICATION FLAGS
+ // START AUTOFILL REMOVE PRE_TRIGGER FLAGS
+
+ /**
+ * Whether pre-trigger flow is disabled.
+ *
+ * @hide
+ */
+ public static final String DEVICE_CONFIG_IMPROVE_FILL_DIALOG_ENABLED = "improve_fill_dialog";
+
+ /**
+ * Minimum amount of time (in milliseconds) to wait after IME animation finishes, and before
+ * starting fill dialog animation.
+ *
+ * @hide
+ */
+ public static final String DEVICE_CONFIG_FILL_DIALOG_MIN_WAIT_AFTER_IME_ANIMATION_END_MS =
+ "fill_dialog_min_wait_after_animation_end_ms";
+
+ /**
+ * Sets a value of timeout in milliseconds, measured after animation end, during which fill
+ * dialog can be shown. If we are at time > animation_end_time + this timeout, fill dialog
+ * wouldn't be shown.
+ *
+ * @hide
+ */
+ public static final String DEVICE_CONFIG_FILL_DIALOG_TIMEOUT_MS = "fill_dialog_timeout_ms";
+
+ // END AUTOFILL REMOVE PRE_TRIGGER FLAGS
+
/**
* Define the max input length for autofill to show suggesiton UI
*
@@ -366,6 +395,17 @@ public class AutofillFeatureFlags {
DEFAULT_AFAA_SHOULD_INCLUDE_ALL_AUTOFILL_TYPE_NOT_NONE_VIEWS_IN_ASSIST_STRUCTURE = true;
// END AUTOFILL FOR ALL APPS DEFAULTS
+ // START AUTOFILL REMOVE PRE_TRIGGER FLAGS DEFAULTS
+ // Default for whether the pre trigger removal is enabled.
+ /** @hide */
+ public static final boolean DEFAULT_IMPROVE_FILL_DIALOG_ENABLED = true;
+ // Default for whether the pre trigger removal is enabled.
+ /** @hide */
+ public static final long DEFAULT_FILL_DIALOG_TIMEOUT_MS = 300; // 300 ms
+ /** @hide */
+ public static final long DEFAULT_FILL_DIALOG_MIN_WAIT_AFTER_IME_ANIMATION_END_MS = 0; // 0 ms
+ // END AUTOFILL REMOVE PRE_TRIGGER FLAGS DEFAULTS
+
/**
* @hide
*/
@@ -611,4 +651,48 @@ public class AutofillFeatureFlags {
}
// END AUTOFILL PCC CLASSIFICATION FUNCTIONS
+
+
+ // START AUTOFILL REMOVE PRE_TRIGGER
+ /**
+ * Whether Autofill Pre Trigger Removal is enabled.
+ *
+ * @hide
+ */
+ public static boolean isImproveFillDialogEnabled() {
+ // TODO(b/266379948): Add condition for checking whether device has PCC first
+
+ return DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_AUTOFILL,
+ DEVICE_CONFIG_IMPROVE_FILL_DIALOG_ENABLED,
+ DEFAULT_IMPROVE_FILL_DIALOG_ENABLED);
+ }
+
+ /**
+ * Whether Autofill Pre Trigger Removal is enabled.
+ *
+ * @hide
+ */
+ public static long getFillDialogTimeoutMs() {
+ // TODO(b/266379948): Add condition for checking whether device has PCC first
+
+ return DeviceConfig.getLong(
+ DeviceConfig.NAMESPACE_AUTOFILL,
+ DEVICE_CONFIG_FILL_DIALOG_TIMEOUT_MS,
+ DEFAULT_FILL_DIALOG_TIMEOUT_MS);
+ }
+
+ /**
+ * Whether Autofill Pre Trigger Removal is enabled.
+ *
+ * @hide
+ */
+ public static long getFillDialogMinWaitAfterImeAnimationtEndMs() {
+ // TODO(b/266379948): Add condition for checking whether device has PCC first
+
+ return DeviceConfig.getLong(
+ DeviceConfig.NAMESPACE_AUTOFILL,
+ DEVICE_CONFIG_FILL_DIALOG_MIN_WAIT_AFTER_IME_ANIMATION_END_MS,
+ DEFAULT_FILL_DIALOG_MIN_WAIT_AFTER_IME_ANIMATION_END_MS);
+ }
}
diff --git a/core/java/android/view/inputmethod/flags.aconfig b/core/java/android/view/inputmethod/flags.aconfig
index aa4927ee9b9c..edd9d6cff799 100644
--- a/core/java/android/view/inputmethod/flags.aconfig
+++ b/core/java/android/view/inputmethod/flags.aconfig
@@ -158,3 +158,11 @@ flag {
purpose: PURPOSE_BUGFIX
}
}
+
+flag {
+ name: "writing_tools"
+ namespace: "input_method"
+ description: "Writing tools API"
+ bug: "373788889"
+ is_fixed_read_only: true
+} \ No newline at end of file
diff --git a/core/java/android/window/DesktopModeFlags.java b/core/java/android/window/DesktopModeFlags.java
index dae87ddcb1bd..6b5a367ab460 100644
--- a/core/java/android/window/DesktopModeFlags.java
+++ b/core/java/android/window/DesktopModeFlags.java
@@ -75,7 +75,8 @@ public enum DesktopModeFlags {
Flags::enableDesktopAppLaunchAlttabTransitions, false),
ENABLE_DESKTOP_APP_LAUNCH_TRANSITIONS(
Flags::enableDesktopAppLaunchTransitions, false),
- ENABLE_DESKTOP_WINDOWING_PERSISTENCE(Flags::enableDesktopWindowingPersistence, false);
+ ENABLE_DESKTOP_WINDOWING_PERSISTENCE(Flags::enableDesktopWindowingPersistence, false),
+ ENABLE_HANDLE_INPUT_FIX(Flags::enableHandleInputFix, true);
private static final String TAG = "DesktopModeFlagsUtil";
// Function called to obtain aconfig flag value.
diff --git a/core/java/com/android/internal/telephony/IPhoneStateListener.aidl b/core/java/com/android/internal/telephony/IPhoneStateListener.aidl
index b5c87868af12..0e85e046e1b6 100644
--- a/core/java/com/android/internal/telephony/IPhoneStateListener.aidl
+++ b/core/java/com/android/internal/telephony/IPhoneStateListener.aidl
@@ -27,6 +27,7 @@ import android.telephony.PhoneCapability;
import android.telephony.PhysicalChannelConfig;
import android.telephony.PreciseCallState;
import android.telephony.PreciseDataConnectionState;
+import android.telephony.satellite.NtnSignalStrength;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.emergency.EmergencyNumber;
@@ -85,4 +86,5 @@ oneway interface IPhoneStateListener {
void onCarrierRoamingNtnModeChanged(in boolean active);
void onCarrierRoamingNtnEligibleStateChanged(in boolean eligible);
void onCarrierRoamingNtnAvailableServicesChanged(in int[] availableServices);
+ void onCarrierRoamingNtnSignalStrengthChanged(in NtnSignalStrength ntnSignalStrength);
}
diff --git a/core/java/com/android/internal/telephony/ITelephonyRegistry.aidl b/core/java/com/android/internal/telephony/ITelephonyRegistry.aidl
index 1c76a6cd4bba..0f268d5de62b 100644
--- a/core/java/com/android/internal/telephony/ITelephonyRegistry.aidl
+++ b/core/java/com/android/internal/telephony/ITelephonyRegistry.aidl
@@ -29,6 +29,7 @@ import android.telephony.ims.ImsReasonInfo;
import android.telephony.PhoneCapability;
import android.telephony.PhysicalChannelConfig;
import android.telephony.PreciseDataConnectionState;
+import android.telephony.satellite.NtnSignalStrength;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.emergency.EmergencyNumber;
@@ -125,8 +126,10 @@ interface ITelephonyRegistry {
void notifyCarrierRoamingNtnModeChanged(int subId, in boolean active);
void notifyCarrierRoamingNtnEligibleStateChanged(int subId, in boolean eligible);
void notifyCarrierRoamingNtnAvailableServicesChanged(int subId, in int[] availableServices);
+ void notifyCarrierRoamingNtnSignalStrengthChanged(int subId, in NtnSignalStrength ntnSignalStrength);
void addSatelliteStateChangeListener(ISatelliteStateChangeListener listener, String pkg, String featureId);
void removeSatelliteStateChangeListener(ISatelliteStateChangeListener listener, String pkg);
void notifySatelliteStateChanged(boolean isEnabled);
+
}
diff --git a/core/java/com/android/internal/widget/NotificationProgressDrawable.java b/core/java/com/android/internal/widget/NotificationProgressDrawable.java
index 30deb499594c..fb6937c94a3e 100644
--- a/core/java/com/android/internal/widget/NotificationProgressDrawable.java
+++ b/core/java/com/android/internal/widget/NotificationProgressDrawable.java
@@ -63,6 +63,7 @@ public final class NotificationProgressDrawable extends Drawable {
private final ArrayList<Part> mParts = new ArrayList<>();
+ private final RectF mSegRectF = new RectF();
private final Rect mPointRect = new Rect();
private final RectF mPointRectF = new RectF();
@@ -198,22 +199,42 @@ public final class NotificationProgressDrawable extends Drawable {
mState.mSegSegGap, x + segWidth, totalWidth);
final float end = x + segWidth - endOffset;
- // Transparent is not allowed (and also is the default in the data), so use that
- // as a sentinel to be replaced by default
- mStrokePaint.setColor(segment.mColor != Color.TRANSPARENT ? segment.mColor
- : mState.mStrokeColor);
- mDashedStrokePaint.setColor(segment.mColor != Color.TRANSPARENT ? segment.mColor
- : mState.mFadedStrokeColor);
-
- // Leave space for the rounded line cap which extends beyond start/end.
- final float capWidth = mStrokePaint.getStrokeWidth() / 2F;
-
- canvas.drawLine(start + capWidth, centerY, end - capWidth, centerY,
- segment.mDashed ? mDashedStrokePaint : mStrokePaint);
-
// Advance the current position to account for the segment's fraction of the total
// width (ignoring offset and padding)
x += segWidth;
+
+ // No space left to draw the segment
+ if (start > end) continue;
+
+ if (segment.mDashed) {
+ // No caps when the segment is dashed.
+
+ mDashedStrokePaint.setColor(segment.mColor != Color.TRANSPARENT ? segment.mColor
+ : mState.mFadedStrokeColor);
+ canvas.drawLine(start, centerY, end, centerY, mDashedStrokePaint);
+ } else if (end - start < mState.mStrokeWidth) {
+ // Not enough segment length to draw the caps
+
+ final float rad = (end - start) / 2F;
+ final float capWidth = mStrokePaint.getStrokeWidth() / 2F;
+
+ mFillPaint.setColor(segment.mColor != Color.TRANSPARENT ? segment.mColor
+ : mState.mStrokeColor);
+
+ mSegRectF.set(start, centerY - capWidth, end, centerY + capWidth);
+ canvas.drawRoundRect(mSegRectF, rad, rad, mFillPaint);
+ } else {
+ // Leave space for the rounded line cap which extends beyond start/end.
+ final float capWidth = mStrokePaint.getStrokeWidth() / 2F;
+
+ // Transparent is not allowed (and also is the default in the data), so use that
+ // as a sentinel to be replaced by default
+ mStrokePaint.setColor(segment.mColor != Color.TRANSPARENT ? segment.mColor
+ : mState.mStrokeColor);
+
+ canvas.drawLine(start + capWidth, centerY, end - capWidth, centerY,
+ mStrokePaint);
+ }
} else if (part instanceof Point point) {
final float pointWidth = 2 * pointRadius;
float start = x - pointRadius;
@@ -232,7 +253,7 @@ public final class NotificationProgressDrawable extends Drawable {
} else {
// TODO: b/367804171 - actually use a vector asset for the default point
// rather than drawing it as a box?
- mPointRectF.set(mPointRect);
+ mPointRectF.set(start, centerY - pointRadius, end, centerY + pointRadius);
final float inset = mState.mPointRectInset;
final float cornerRadius = mState.mPointRectCornerRadius;
mPointRectF.inset(inset, inset);
diff --git a/core/jni/android_hardware_input_InputWindowHandle.cpp b/core/jni/android_hardware_input_InputWindowHandle.cpp
index 69f633420a0d..f1c4913fe006 100644
--- a/core/jni/android_hardware_input_InputWindowHandle.cpp
+++ b/core/jni/android_hardware_input_InputWindowHandle.cpp
@@ -83,68 +83,53 @@ static struct {
jmethodID ctor;
} gRegionClassInfo;
-static Mutex gHandleMutex;
-
-
-// --- NativeInputWindowHandle ---
-
-NativeInputWindowHandle::NativeInputWindowHandle(jweak objWeak) :
- mObjWeak(objWeak) {
-}
-
-NativeInputWindowHandle::~NativeInputWindowHandle() {
- JNIEnv* env = AndroidRuntime::getJNIEnv();
- env->DeleteWeakGlobalRef(mObjWeak);
+// --- Global functions ---
- // Clear the weak reference to the layer handle and flush any binder ref count operations so we
- // do not hold on to any binder references.
- // TODO(b/139697085) remove this after it can be flushed automatically
- mInfo.touchableRegionCropHandle.clear();
- IPCThreadState::self()->flushCommands();
-}
+sp<gui::WindowInfoHandle> android_view_InputWindowHandle_getHandle(JNIEnv* env, jobject obj) {
+ sp<gui::WindowInfoHandle> handle = [&]() {
+ jlong cachedHandle = env->GetLongField(obj, gInputWindowHandleClassInfo.ptr);
+ if (cachedHandle) {
+ return sp<gui::WindowInfoHandle>::fromExisting(
+ reinterpret_cast<gui::WindowInfoHandle*>(cachedHandle));
+ }
-jobject NativeInputWindowHandle::getInputWindowHandleObjLocalRef(JNIEnv* env) {
- return env->NewLocalRef(mObjWeak);
-}
+ auto newHandle = sp<gui::WindowInfoHandle>::make();
+ newHandle->incStrong((void*)android_view_InputWindowHandle_getHandle);
+ env->SetLongField(obj, gInputWindowHandleClassInfo.ptr,
+ reinterpret_cast<jlong>(newHandle.get()));
+ return newHandle;
+ }();
-bool NativeInputWindowHandle::updateInfo() {
- JNIEnv* env = AndroidRuntime::getJNIEnv();
- jobject obj = env->NewLocalRef(mObjWeak);
- if (!obj) {
- releaseChannel();
- return false;
- }
+ gui::WindowInfo* windowInfo = handle->editInfo();
- mInfo.touchableRegion.clear();
+ windowInfo->touchableRegion.clear();
jobject tokenObj = env->GetObjectField(obj, gInputWindowHandleClassInfo.token);
if (tokenObj) {
- mInfo.token = ibinderForJavaObject(env, tokenObj);
+ windowInfo->token = ibinderForJavaObject(env, tokenObj);
env->DeleteLocalRef(tokenObj);
} else {
- mInfo.token.clear();
+ windowInfo->token.clear();
}
- mInfo.name = getStringField(env, obj, gInputWindowHandleClassInfo.name, "<null>");
+ windowInfo->name = getStringField(env, obj, gInputWindowHandleClassInfo.name, "<null>");
- mInfo.dispatchingTimeout = std::chrono::milliseconds(
+ windowInfo->dispatchingTimeout = std::chrono::milliseconds(
env->GetLongField(obj, gInputWindowHandleClassInfo.dispatchingTimeoutMillis));
ScopedLocalRef<jobject> frameObj(env,
env->GetObjectField(obj, gInputWindowHandleClassInfo.frame));
- mInfo.frame = JNICommon::rectFromObj(env, frameObj.get());
+ windowInfo->frame = JNICommon::rectFromObj(env, frameObj.get());
- mInfo.surfaceInset = env->GetIntField(obj,
- gInputWindowHandleClassInfo.surfaceInset);
- mInfo.globalScaleFactor = env->GetFloatField(obj,
- gInputWindowHandleClassInfo.scaleFactor);
+ windowInfo->surfaceInset = env->GetIntField(obj, gInputWindowHandleClassInfo.surfaceInset);
+ windowInfo->globalScaleFactor =
+ env->GetFloatField(obj, gInputWindowHandleClassInfo.scaleFactor);
- jobject regionObj = env->GetObjectField(obj,
- gInputWindowHandleClassInfo.touchableRegion);
+ jobject regionObj = env->GetObjectField(obj, gInputWindowHandleClassInfo.touchableRegion);
if (regionObj) {
for (graphics::RegionIterator it(env, regionObj); !it.isDone(); it.next()) {
ARect rect = it.getRect();
- mInfo.addTouchableRegion(Rect(rect.left, rect.top, rect.right, rect.bottom));
+ windowInfo->addTouchableRegion(Rect(rect.left, rect.top, rect.right, rect.bottom));
}
env->DeleteLocalRef(regionObj);
}
@@ -153,49 +138,55 @@ bool NativeInputWindowHandle::updateInfo() {
env->GetIntField(obj, gInputWindowHandleClassInfo.layoutParamsFlags));
const auto type = static_cast<WindowInfo::Type>(
env->GetIntField(obj, gInputWindowHandleClassInfo.layoutParamsType));
- mInfo.layoutParamsFlags = flags;
- mInfo.layoutParamsType = type;
+ windowInfo->layoutParamsFlags = flags;
+ windowInfo->layoutParamsType = type;
- mInfo.inputConfig = static_cast<gui::WindowInfo::InputConfig>(
+ windowInfo->inputConfig = static_cast<gui::WindowInfo::InputConfig>(
env->GetIntField(obj, gInputWindowHandleClassInfo.inputConfig));
- mInfo.touchOcclusionMode = static_cast<TouchOcclusionMode>(
+ windowInfo->touchOcclusionMode = static_cast<TouchOcclusionMode>(
env->GetIntField(obj, gInputWindowHandleClassInfo.touchOcclusionMode));
- mInfo.ownerPid = gui::Pid{env->GetIntField(obj, gInputWindowHandleClassInfo.ownerPid)};
- mInfo.ownerUid = gui::Uid{
+ windowInfo->ownerPid = gui::Pid{env->GetIntField(obj, gInputWindowHandleClassInfo.ownerPid)};
+ windowInfo->ownerUid = gui::Uid{
static_cast<uid_t>(env->GetIntField(obj, gInputWindowHandleClassInfo.ownerUid))};
- mInfo.packageName = getStringField(env, obj, gInputWindowHandleClassInfo.packageName, "<null>");
- mInfo.displayId =
+ windowInfo->packageName =
+ getStringField(env, obj, gInputWindowHandleClassInfo.packageName, "<null>");
+ windowInfo->displayId =
ui::LogicalDisplayId{env->GetIntField(obj, gInputWindowHandleClassInfo.displayId)};
- jobject inputApplicationHandleObj = env->GetObjectField(obj,
- gInputWindowHandleClassInfo.inputApplicationHandle);
+ jobject inputApplicationHandleObj =
+ env->GetObjectField(obj, gInputWindowHandleClassInfo.inputApplicationHandle);
if (inputApplicationHandleObj) {
std::shared_ptr<InputApplicationHandle> inputApplicationHandle =
android_view_InputApplicationHandle_getHandle(env, inputApplicationHandleObj);
if (inputApplicationHandle != nullptr) {
inputApplicationHandle->updateInfo();
- mInfo.applicationInfo = *(inputApplicationHandle->getInfo());
+ windowInfo->applicationInfo = *(inputApplicationHandle->getInfo());
}
env->DeleteLocalRef(inputApplicationHandleObj);
}
- mInfo.replaceTouchableRegionWithCrop = env->GetBooleanField(obj,
- gInputWindowHandleClassInfo.replaceTouchableRegionWithCrop);
+ windowInfo->replaceTouchableRegionWithCrop =
+ env->GetBooleanField(obj, gInputWindowHandleClassInfo.replaceTouchableRegionWithCrop);
- jobject weakSurfaceCtrl = env->GetObjectField(obj,
- gInputWindowHandleClassInfo.touchableRegionSurfaceControl.ctrl);
+ jobject weakSurfaceCtrl =
+ env->GetObjectField(obj,
+ gInputWindowHandleClassInfo.touchableRegionSurfaceControl.ctrl);
bool touchableRegionCropHandleSet = false;
if (weakSurfaceCtrl) {
// Promote java weak reference.
- jobject strongSurfaceCtrl = env->CallObjectMethod(weakSurfaceCtrl,
- gInputWindowHandleClassInfo.touchableRegionSurfaceControl.get);
+ jobject strongSurfaceCtrl =
+ env->CallObjectMethod(weakSurfaceCtrl,
+ gInputWindowHandleClassInfo.touchableRegionSurfaceControl
+ .get);
if (strongSurfaceCtrl) {
- jlong mNativeObject = env->GetLongField(strongSurfaceCtrl,
- gInputWindowHandleClassInfo.touchableRegionSurfaceControl.mNativeObject);
+ jlong mNativeObject =
+ env->GetLongField(strongSurfaceCtrl,
+ gInputWindowHandleClassInfo.touchableRegionSurfaceControl
+ .mNativeObject);
if (mNativeObject) {
auto ctrl = reinterpret_cast<SurfaceControl *>(mNativeObject);
- mInfo.touchableRegionCropHandle = ctrl->getHandle();
+ windowInfo->touchableRegionCropHandle = ctrl->getHandle();
touchableRegionCropHandleSet = true;
}
env->DeleteLocalRef(strongSurfaceCtrl);
@@ -203,15 +194,15 @@ bool NativeInputWindowHandle::updateInfo() {
env->DeleteLocalRef(weakSurfaceCtrl);
}
if (!touchableRegionCropHandleSet) {
- mInfo.touchableRegionCropHandle.clear();
+ windowInfo->touchableRegionCropHandle.clear();
}
jobject windowTokenObj = env->GetObjectField(obj, gInputWindowHandleClassInfo.windowToken);
if (windowTokenObj) {
- mInfo.windowToken = ibinderForJavaObject(env, windowTokenObj);
+ windowInfo->windowToken = ibinderForJavaObject(env, windowTokenObj);
env->DeleteLocalRef(windowTokenObj);
} else {
- mInfo.windowToken.clear();
+ windowInfo->windowToken.clear();
}
ScopedLocalRef<jobject>
@@ -220,41 +211,16 @@ bool NativeInputWindowHandle::updateInfo() {
gInputWindowHandleClassInfo
.focusTransferTarget));
if (focusTransferTargetObj.get()) {
- mInfo.focusTransferTarget = ibinderForJavaObject(env, focusTransferTargetObj.get());
+ windowInfo->focusTransferTarget = ibinderForJavaObject(env, focusTransferTargetObj.get());
} else {
- mInfo.focusTransferTarget.clear();
+ windowInfo->focusTransferTarget.clear();
}
- env->DeleteLocalRef(obj);
- return true;
-}
-
-
-// --- Global functions ---
-
-sp<NativeInputWindowHandle> android_view_InputWindowHandle_getHandle(
- JNIEnv* env, jobject inputWindowHandleObj) {
- if (!inputWindowHandleObj) {
- return NULL;
- }
-
- AutoMutex _l(gHandleMutex);
-
- jlong ptr = env->GetLongField(inputWindowHandleObj, gInputWindowHandleClassInfo.ptr);
- NativeInputWindowHandle* handle;
- if (ptr) {
- handle = reinterpret_cast<NativeInputWindowHandle*>(ptr);
- } else {
- jweak objWeak = env->NewWeakGlobalRef(inputWindowHandleObj);
- handle = new NativeInputWindowHandle(objWeak);
- handle->incStrong((void*)android_view_InputWindowHandle_getHandle);
- env->SetLongField(inputWindowHandleObj, gInputWindowHandleClassInfo.ptr,
- reinterpret_cast<jlong>(handle));
- }
return handle;
}
-jobject android_view_InputWindowHandle_fromWindowInfo(JNIEnv* env, gui::WindowInfo windowInfo) {
+jobject android_view_InputWindowHandle_fromWindowInfo(JNIEnv* env,
+ const gui::WindowInfo& windowInfo) {
ScopedLocalRef<jobject>
applicationHandle(env,
android_view_InputApplicationHandle_fromInputApplicationInfo(
@@ -337,18 +303,15 @@ jobject android_view_InputWindowHandle_fromWindowInfo(JNIEnv* env, gui::WindowIn
// --- JNI ---
static void android_view_InputWindowHandle_nativeDispose(JNIEnv* env, jobject obj) {
- AutoMutex _l(gHandleMutex);
-
jlong ptr = env->GetLongField(obj, gInputWindowHandleClassInfo.ptr);
- if (ptr) {
- env->SetLongField(obj, gInputWindowHandleClassInfo.ptr, 0);
-
- NativeInputWindowHandle* handle = reinterpret_cast<NativeInputWindowHandle*>(ptr);
- handle->decStrong((void*)android_view_InputWindowHandle_getHandle);
+ if (!ptr) {
+ return;
}
+ env->SetLongField(obj, gInputWindowHandleClassInfo.ptr, 0);
+ auto handle = reinterpret_cast<gui::WindowInfoHandle*>(ptr);
+ handle->decStrong((void*)android_view_InputWindowHandle_getHandle);
}
-
static const JNINativeMethod gInputWindowHandleMethods[] = {
/* name, signature, funcPtr */
{ "nativeDispose", "()V",
diff --git a/core/jni/android_hardware_input_InputWindowHandle.h b/core/jni/android_hardware_input_InputWindowHandle.h
index 408e0f1bfa36..aa375e9ef477 100644
--- a/core/jni/android_hardware_input_InputWindowHandle.h
+++ b/core/jni/android_hardware_input_InputWindowHandle.h
@@ -24,24 +24,11 @@
namespace android {
-class NativeInputWindowHandle : public gui::WindowInfoHandle {
-public:
- NativeInputWindowHandle(jweak objWeak);
- virtual ~NativeInputWindowHandle();
+sp<gui::WindowInfoHandle> android_view_InputWindowHandle_getHandle(JNIEnv* env,
+ jobject inputWindowHandleObj);
- jobject getInputWindowHandleObjLocalRef(JNIEnv* env);
-
- virtual bool updateInfo();
-
-private:
- jweak mObjWeak;
-};
-
-extern sp<NativeInputWindowHandle> android_view_InputWindowHandle_getHandle(
- JNIEnv* env, jobject inputWindowHandleObj);
-
-extern jobject android_view_InputWindowHandle_fromWindowInfo(JNIEnv* env,
- gui::WindowInfo windowInfo);
+jobject android_view_InputWindowHandle_fromWindowInfo(JNIEnv* env,
+ const gui::WindowInfo& windowInfo);
} // namespace android
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index 56292c3d0fb2..d3bf36e60345 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -979,14 +979,16 @@ static void nativeSetAlpha(JNIEnv* env, jclass clazz, jlong transactionObj,
static void nativeSetInputWindowInfo(JNIEnv* env, jclass clazz, jlong transactionObj,
jlong nativeObject, jobject inputWindow) {
- auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj);
+ if (!inputWindow) {
+ jniThrowNullPointerException(env, "InputWindowHandle is null");
+ return;
+ }
- sp<NativeInputWindowHandle> handle = android_view_InputWindowHandle_getHandle(
- env, inputWindow);
- handle->updateInfo();
+ auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj);
+ sp<gui::WindowInfoHandle> info = android_view_InputWindowHandle_getHandle(env, inputWindow);
auto ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
- transaction->setInputWindowInfo(ctrl, *handle->getInfo());
+ transaction->setInputWindowInfo(ctrl, std::move(info));
}
static void nativeAddWindowInfosReportedListener(JNIEnv* env, jclass clazz, jlong transactionObj,
diff --git a/core/proto/android/providers/settings/secure.proto b/core/proto/android/providers/settings/secure.proto
index 606e829c41fa..6af742fb23f4 100644
--- a/core/proto/android/providers/settings/secure.proto
+++ b/core/proto/android/providers/settings/secure.proto
@@ -104,6 +104,7 @@ message SecureSettingsProto {
optional SettingProto accessibility_single_finger_panning_enabled = 56 [ (android.privacy).dest = DEST_AUTOMATIC ];
optional SettingProto accessibility_gesture_targets = 57 [ (android.privacy).dest = DEST_AUTOMATIC ];
optional SettingProto display_daltonizer_saturation_level = 58 [ (android.privacy).dest = DEST_AUTOMATIC ];
+ optional SettingProto accessibility_key_gesture_targets = 59 [ (android.privacy).dest = DEST_AUTOMATIC ];
}
optional Accessibility accessibility = 2;
diff --git a/core/tests/coretests/src/android/app/PropertyInvalidatedCacheTests.java b/core/tests/coretests/src/android/app/PropertyInvalidatedCacheTests.java
index da1fffa0fac4..a2598f69e031 100644
--- a/core/tests/coretests/src/android/app/PropertyInvalidatedCacheTests.java
+++ b/core/tests/coretests/src/android/app/PropertyInvalidatedCacheTests.java
@@ -16,6 +16,7 @@
package android.app;
+import static android.app.Flags.FLAG_PIC_ISOLATE_CACHE_BY_UID;
import static android.app.PropertyInvalidatedCache.NONCE_UNSET;
import static android.app.PropertyInvalidatedCache.MODULE_BLUETOOTH;
import static android.app.PropertyInvalidatedCache.MODULE_SYSTEM;
@@ -30,8 +31,9 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import android.app.PropertyInvalidatedCache.Args;
import android.annotation.SuppressLint;
+import android.app.PropertyInvalidatedCache.Args;
+import android.os.Binder;
import com.android.internal.os.ApplicationSharedMemory;
import android.platform.test.annotations.IgnoreUnderRavenwood;
@@ -58,6 +60,7 @@ import org.junit.Test;
*/
@SmallTest
public class PropertyInvalidatedCacheTests {
+ @Rule
public final CheckFlagsRule mCheckFlagsRule =
DeviceFlagsValueProvider.createCheckFlagsRule();
@@ -455,8 +458,9 @@ public class PropertyInvalidatedCacheTests {
// Test the Args-style constructor.
@Test
public void testArgsConstructor() {
- // Create a cache with a maximum of four entries.
- TestCache cache = new TestCache(new Args(MODULE_TEST).api("init1").maxEntries(4),
+ // Create a cache with a maximum of four entries and non-isolated UIDs.
+ TestCache cache = new TestCache(new Args(MODULE_TEST)
+ .maxEntries(4).isolateUids(false).api("init1"),
new TestQuery());
cache.invalidateCache();
@@ -570,4 +574,73 @@ public class PropertyInvalidatedCacheTests {
// Expected exception.
}
}
+
+ // Verify that a cache created with isolatedUids(true) separates out the results.
+ @RequiresFlagsEnabled(FLAG_PIC_ISOLATE_CACHE_BY_UID)
+ @Test
+ public void testIsolatedUids() {
+ TestCache cache = new TestCache(new Args(MODULE_TEST)
+ .maxEntries(4).isolateUids(true).api("testIsolatedUids").testMode(true),
+ new TestQuery());
+ cache.invalidateCache();
+ final int uid1 = 1;
+ final int uid2 = 2;
+
+ long token = Binder.setCallingWorkSourceUid(uid1);
+ try {
+ // Populate the cache for user 1
+ assertEquals("foo5", cache.query(5));
+ assertEquals(1, cache.getRecomputeCount());
+ assertEquals("foo5", cache.query(5));
+ assertEquals(1, cache.getRecomputeCount());
+ assertEquals("foo6", cache.query(6));
+ assertEquals(2, cache.getRecomputeCount());
+
+ // Populate the cache for user 2. User 1 values are not reused.
+ Binder.setCallingWorkSourceUid(uid2);
+ assertEquals("foo5", cache.query(5));
+ assertEquals(3, cache.getRecomputeCount());
+ assertEquals("foo5", cache.query(5));
+ assertEquals(3, cache.getRecomputeCount());
+
+ // Verify that the cache for user 1 is still populated.
+ Binder.setCallingWorkSourceUid(uid1);
+ assertEquals("foo5", cache.query(5));
+ assertEquals(3, cache.getRecomputeCount());
+
+ } finally {
+ Binder.restoreCallingWorkSource(token);
+ }
+
+ // Repeat the test with a non-isolated cache.
+ cache = new TestCache(new Args(MODULE_TEST)
+ .maxEntries(4).isolateUids(false).api("testIsolatedUids2").testMode(true),
+ new TestQuery());
+ cache.invalidateCache();
+ token = Binder.setCallingWorkSourceUid(uid1);
+ try {
+ // Populate the cache for user 1
+ assertEquals("foo5", cache.query(5));
+ assertEquals(1, cache.getRecomputeCount());
+ assertEquals("foo5", cache.query(5));
+ assertEquals(1, cache.getRecomputeCount());
+ assertEquals("foo6", cache.query(6));
+ assertEquals(2, cache.getRecomputeCount());
+
+ // Populate the cache for user 2. User 1 values are reused.
+ Binder.setCallingWorkSourceUid(uid2);
+ assertEquals("foo5", cache.query(5));
+ assertEquals(2, cache.getRecomputeCount());
+ assertEquals("foo5", cache.query(5));
+ assertEquals(2, cache.getRecomputeCount());
+
+ // Verify that the cache for user 1 is still populated.
+ Binder.setCallingWorkSourceUid(uid1);
+ assertEquals("foo5", cache.query(5));
+ assertEquals(2, cache.getRecomputeCount());
+
+ } finally {
+ Binder.restoreCallingWorkSource(token);
+ }
+ }
}
diff --git a/core/tests/coretests/src/android/content/IntentTest.java b/core/tests/coretests/src/android/content/IntentTest.java
index 7bc4abd935b6..d169ce3c07d0 100644
--- a/core/tests/coretests/src/android/content/IntentTest.java
+++ b/core/tests/coretests/src/android/content/IntentTest.java
@@ -37,10 +37,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
/**
* Build/Install/Run:
* atest FrameworksCoreTests:IntentTest
@@ -61,12 +57,7 @@ public class IntentTest {
public void testReadFromParcelWithExtraIntentKeys() {
Intent intent = new Intent("TEST_ACTION");
intent.putExtra(TEST_EXTRA_NAME, new Intent(TEST_ACTION));
- // Not an intent, don't count.
intent.putExtra(TEST_EXTRA_NAME + "2", 1);
- ArrayList<Intent> intents = new ArrayList<>();
- intents.add(new Intent(TEST_ACTION));
- intent.putParcelableArrayListExtra(TEST_EXTRA_NAME + "3", intents);
- intent.setClipData(ClipData.newIntent("label", new Intent(TEST_ACTION)));
intent.collectExtraIntentKeys();
final Parcel parcel = Parcel.obtain();
@@ -77,7 +68,7 @@ public class IntentTest {
assertEquals(intent.getAction(), target.getAction());
assertEquals(intent.getExtraIntentKeys(), target.getExtraIntentKeys());
- assertThat(intent.getExtraIntentKeys()).hasSize(3);
+ assertThat(intent.getExtraIntentKeys()).hasSize(1);
}
@Test
@@ -96,37 +87,13 @@ public class IntentTest {
@RequiresFlagsEnabled(Flags.FLAG_PREVENT_INTENT_REDIRECT)
public void testCollectExtraIntentKeys() {
Intent intent = new Intent(TEST_ACTION);
-
- Intent[] intents = new Intent[10];
- for (int i = 0; i < intents.length; i++) {
- intents[i] = new Intent("action" + i);
- }
- Intent[] intents2 = new Intent[2]; // intents[6-7]
- System.arraycopy(intents, 6, intents2, 0, intents2.length);
- ArrayList<Intent> intents3 = new ArrayList<>(2);
- intents3.addAll(Arrays.asList(intents).subList(8, 10)); // intents[8-9]
- intent.putExtra("key1", intents[0]);
- intent.putExtra("array-key", intents2);
- intent.setClipData(ClipData.newIntent("label2", intents[1]));
- intent.putExtra("intkey", 1);
- intents[0].putExtra("key3", intents[2]);
- intents[0].setClipData(ClipData.newIntent("label4", intents[3]));
- intents[0].putParcelableArrayListExtra("array-list-key", intents3);
- intents[1].putExtra("key3", intents[4]);
- intents[1].setClipData(ClipData.newIntent("label4", intents[5]));
- intents[5].putExtra("intkey", 2);
+ Intent extraIntent = new Intent(TEST_ACTION, TEST_URI);
+ intent.putExtra(TEST_EXTRA_NAME, extraIntent);
intent.collectExtraIntentKeys();
- // collect all actions of nested intents.
- final List<String> actions = new ArrayList<>();
- intent.forEachNestedCreatorToken(intent1 -> {
- actions.add(intent1.getAction());
- });
- assertThat(actions).hasSize(10);
- for (int i = 0; i < intents.length; i++) {
- assertThat(actions).contains("action" + i);
- }
+ assertThat(intent.getExtraIntentKeys()).hasSize(1);
+ assertThat(intent.getExtraIntentKeys()).contains(TEST_EXTRA_NAME);
}
}
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index 7ced809d2a3a..541ca602a386 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -594,6 +594,9 @@ applications that come with the platform
<!-- Permission required for CTS test - AdvancedProtectionManagerTest -->
<permission name="android.permission.SET_ADVANCED_PROTECTION_MODE" />
<permission name="android.permission.QUERY_ADVANCED_PROTECTION_MODE" />
+ <!-- Permissions required for CTS test - SettingsPreferenceServiceClientTest -->
+ <permission name="android.permission.READ_SYSTEM_PREFERENCES" />
+ <permission name="android.permission.WRITE_SYSTEM_PREFERENCES" />
</privapp-permissions>
<privapp-permissions package="com.android.statementservice">
diff --git a/data/keyboards/Generic.kl b/data/keyboards/Generic.kl
index f8d3bffbe00b..2b0802b54c14 100644
--- a/data/keyboards/Generic.kl
+++ b/data/keyboards/Generic.kl
@@ -171,7 +171,7 @@ key 143 WAKEUP
# key 149 "KEY_PROG2"
key 150 EXPLORER
# key 151 "KEY_MSDOS"
-key 152 POWER
+key 152 LOCK
# key 153 "KEY_DIRECTION"
# key 154 "KEY_CYCLEWINDOWS"
key 155 ENVELOPE
@@ -200,20 +200,20 @@ key 177 PAGE_UP
key 178 PAGE_DOWN
key 179 NUMPAD_LEFT_PAREN
key 180 NUMPAD_RIGHT_PAREN
-# key 181 "KEY_NEW"
+key 181 NEW
# key 182 "KEY_REDO"
-# key 183 F13
-# key 184 F14
-# key 185 F15
-# key 186 F16
-# key 187 F17
-# key 188 F18
-# key 189 F19
-# key 190 F20
-# key 191 F21
-# key 192 F22
-# key 193 F23
-# key 194 F24
+key 183 F13
+key 184 F14
+key 185 F15
+key 186 F16
+key 187 F17
+key 188 F18
+key 189 F19
+key 190 F20
+key 191 F21
+key 192 F22
+key 193 F23
+key 194 F24
# key 195 (undefined)
# key 196 (undefined)
# key 197 (undefined)
@@ -225,11 +225,11 @@ key 201 MEDIA_PAUSE
# key 203 "KEY_PROG4"
key 204 NOTIFICATION
# key 205 "KEY_SUSPEND"
-# key 206 "KEY_CLOSE"
+key 206 CLOSE
key 207 MEDIA_PLAY
key 208 MEDIA_FAST_FORWARD
# key 209 "KEY_BASSBOOST"
-# key 210 "KEY_PRINT"
+key 210 PRINT
# key 211 "KEY_HP"
key 212 CAMERA
key 213 MUSIC
@@ -328,7 +328,7 @@ key 368 LANGUAGE_SWITCH
# key 369 "KEY_TITLE"
key 370 CAPTIONS
# key 371 "KEY_ANGLE"
-# key 372 "KEY_ZOOM"
+key 372 FULLSCREEN
# key 373 "KEY_MODE"
# key 374 "KEY_KEYBOARD"
# key 375 "KEY_SCREEN"
@@ -425,12 +425,15 @@ key 582 VOICE_ASSIST
# Linux KEY_ASSISTANT
key 583 ASSIST
key 585 EMOJI_PICKER
+key 586 DICTATE
key 656 MACRO_1
key 657 MACRO_2
key 658 MACRO_3
key 659 MACRO_4
# Keys defined by HID usages
+key usage 0x010082 LOCK FALLBACK_USAGE_MAPPING
+key usage 0x01009B DO_NOT_DISTURB FALLBACK_USAGE_MAPPING
key usage 0x0c0065 SCREENSHOT FALLBACK_USAGE_MAPPING
key usage 0x0c0067 WINDOW FALLBACK_USAGE_MAPPING
key usage 0x0c006F BRIGHTNESS_UP FALLBACK_USAGE_MAPPING
@@ -438,12 +441,17 @@ key usage 0x0c0070 BRIGHTNESS_DOWN FALLBACK_USAGE_MAPPING
key usage 0x0c0079 KEYBOARD_BACKLIGHT_UP FALLBACK_USAGE_MAPPING
key usage 0x0c007A KEYBOARD_BACKLIGHT_DOWN FALLBACK_USAGE_MAPPING
key usage 0x0c007C KEYBOARD_BACKLIGHT_TOGGLE FALLBACK_USAGE_MAPPING
+key usage 0x0c00D8 DICTATE FALLBACK_USAGE_MAPPING
key usage 0x0c00D9 EMOJI_PICKER FALLBACK_USAGE_MAPPING
key usage 0x0c0173 MEDIA_AUDIO_TRACK FALLBACK_USAGE_MAPPING
key usage 0x0c019C PROFILE_SWITCH FALLBACK_USAGE_MAPPING
key usage 0x0c019F SETTINGS FALLBACK_USAGE_MAPPING
key usage 0x0c01A2 ALL_APPS FALLBACK_USAGE_MAPPING
+key usage 0x0c0201 NEW FALLBACK_USAGE_MAPPING
+key usage 0x0c0203 CLOSE FALLBACK_USAGE_MAPPING
+key usage 0x0c0208 PRINT FALLBACK_USAGE_MAPPING
key usage 0x0c0227 REFRESH FALLBACK_USAGE_MAPPING
+key usage 0x0c0232 FULLSCREEN FALLBACK_USAGE_MAPPING
key usage 0x0c029D LANGUAGE_SWITCH FALLBACK_USAGE_MAPPING
key usage 0x0c029F RECENT_APPS FALLBACK_USAGE_MAPPING
key usage 0x0c02A2 ALL_APPS FALLBACK_USAGE_MAPPING
diff --git a/libs/WindowManager/Shell/res/layout/desktop_mode_window_decor_handle_menu.xml b/libs/WindowManager/Shell/res/layout/desktop_mode_window_decor_handle_menu.xml
index f90e165ffc74..a18a2510f0f7 100644
--- a/libs/WindowManager/Shell/res/layout/desktop_mode_window_decor_handle_menu.xml
+++ b/libs/WindowManager/Shell/res/layout/desktop_mode_window_decor_handle_menu.xml
@@ -168,7 +168,7 @@
</LinearLayout>
<LinearLayout
- android:id="@+id/open_in_browser_pill"
+ android:id="@+id/open_in_app_or_browser_pill"
android:layout_width="match_parent"
android:layout_height="@dimen/desktop_mode_handle_menu_open_in_browser_pill_height"
android:layout_marginTop="@dimen/desktop_mode_handle_menu_pill_spacing_margin"
@@ -178,7 +178,7 @@
android:background="@drawable/desktop_mode_decor_handle_menu_background">
<Button
- android:id="@+id/open_in_browser_button"
+ android:id="@+id/open_in_app_or_browser_button"
android:layout_weight="1"
android:contentDescription="@string/open_in_browser_text"
android:text="@string/open_in_browser_text"
diff --git a/libs/WindowManager/Shell/res/values/strings.xml b/libs/WindowManager/Shell/res/values/strings.xml
index 8f1ef6c7e49e..012579a6d40c 100644
--- a/libs/WindowManager/Shell/res/values/strings.xml
+++ b/libs/WindowManager/Shell/res/values/strings.xml
@@ -301,6 +301,8 @@
<string name="screenshot_text">Screenshot</string>
<!-- Accessibility text for the handle menu open in browser button [CHAR LIMIT=NONE] -->
<string name="open_in_browser_text">Open in browser</string>
+ <!-- Accessibility text for the handle menu open in app button [CHAR LIMIT=NONE] -->
+ <string name="open_in_app_text">Open in App</string>
<!-- Accessibility text for the handle menu new window button [CHAR LIMIT=NONE] -->
<string name="new_window_text">New Window</string>
<!-- Accessibility text for the handle menu new window button [CHAR LIMIT=NONE] -->
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/apptoweb/AppToWebUtils.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/apptoweb/AppToWebUtils.kt
index 65132fe89063..7243ea36b137 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/apptoweb/AppToWebUtils.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/apptoweb/AppToWebUtils.kt
@@ -20,7 +20,9 @@ package com.android.wm.shell.apptoweb
import android.content.Context
import android.content.Intent
+import android.content.Intent.ACTION_VIEW
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
+import android.content.Intent.FLAG_ACTIVITY_REQUIRE_NON_BROWSER
import android.content.pm.PackageManager
import android.content.pm.verify.domain.DomainVerificationManager
import android.content.pm.verify.domain.DomainVerificationUserState
@@ -31,7 +33,7 @@ import com.android.wm.shell.protolog.ShellProtoLogGroup
private const val TAG = "AppToWebUtils"
private val GenericBrowserIntent = Intent()
- .setAction(Intent.ACTION_VIEW)
+ .setAction(ACTION_VIEW)
.addCategory(Intent.CATEGORY_BROWSABLE)
.setData(Uri.parse("http:"))
@@ -67,6 +69,20 @@ fun getBrowserIntent(uri: Uri, packageManager: PackageManager): Intent? {
}
/**
+ * Returns intent if there is a non-browser application available to handle the uri. Otherwise,
+ * returns null.
+ */
+fun getAppIntent(uri: Uri, packageManager: PackageManager): Intent? {
+ val intent = Intent(ACTION_VIEW, uri).apply {
+ flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_REQUIRE_NON_BROWSER
+ }
+ // If there is no application available to handle intent, return null
+ val component = intent.resolveActivity(packageManager) ?: return null
+ intent.setComponent(component)
+ return intent
+}
+
+/**
* Returns the [DomainVerificationUserState] of the user associated with the given
* [DomainVerificationManager] and the given package.
*/
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java
index 999ce17905ef..1f77abe54c8d 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarLayerView.java
@@ -19,6 +19,7 @@ package com.android.wm.shell.bubbles.bar;
import static com.android.wm.shell.shared.animation.Interpolators.ALPHA_IN;
import static com.android.wm.shell.shared.animation.Interpolators.ALPHA_OUT;
import static com.android.wm.shell.bubbles.Bubbles.DISMISS_USER_GESTURE;
+import static com.android.wm.shell.shared.bubbles.BubbleConstants.BUBBLE_EXPANDED_SCRIM_ALPHA;
import android.annotation.Nullable;
import android.content.Context;
@@ -66,8 +67,6 @@ public class BubbleBarLayerView extends FrameLayout
private static final String TAG = BubbleBarLayerView.class.getSimpleName();
- private static final float SCRIM_ALPHA = 0.2f;
-
private final BubbleController mBubbleController;
private final BubbleData mBubbleData;
private final BubblePositioner mPositioner;
@@ -386,7 +385,7 @@ public class BubbleBarLayerView extends FrameLayout
if (show) {
mScrimView.animate()
.setInterpolator(ALPHA_IN)
- .alpha(SCRIM_ALPHA)
+ .alpha(BUBBLE_EXPANDED_SCRIM_ALPHA)
.start();
} else {
mScrimView.animate()
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipAppOpsListener.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipAppOpsListener.kt
index 4abb35c2a428..193c593e2ab2 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipAppOpsListener.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/pip/PipAppOpsListener.kt
@@ -16,8 +16,11 @@
package com.android.wm.shell.common.pip
import android.app.AppOpsManager
+import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
+import android.util.Pair
+import com.android.internal.annotations.VisibleForTesting
import com.android.wm.shell.common.ShellExecutor
class PipAppOpsListener(
@@ -27,10 +30,12 @@ class PipAppOpsListener(
) {
private val mAppOpsManager: AppOpsManager = checkNotNull(
mContext.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager)
+ private var mTopPipActivityInfoSupplier: (Context) -> Pair<ComponentName?, Int> =
+ PipUtils::getTopPipActivity
private val mAppOpsChangedListener = AppOpsManager.OnOpChangedListener { _, packageName ->
try {
// Dismiss the PiP once the user disables the app ops setting for that package
- val topPipActivityInfo = PipUtils.getTopPipActivity(mContext)
+ val topPipActivityInfo = mTopPipActivityInfoSupplier.invoke(mContext)
val componentName = topPipActivityInfo.first ?: return@OnOpChangedListener
val userId = topPipActivityInfo.second
val appInfo = mContext.packageManager
@@ -75,4 +80,9 @@ class PipAppOpsListener(
/** Dismisses the PIP window. */
fun dismissPip()
}
+
+ @VisibleForTesting
+ fun setTopPipActivityInfoSupplier(supplier: (Context) -> Pair<ComponentName?, Int>) {
+ mTopPipActivityInfoSupplier = supplier
+ }
} \ No newline at end of file
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 a472f79c98e6..44fce81fa059 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
@@ -836,14 +836,21 @@ public abstract class WMShellModule {
@Provides
static Optional<DesktopImmersiveController> provideDesktopImmersiveController(
Context context,
+ ShellInit shellInit,
Transitions transitions,
@DynamicOverride DesktopRepository desktopRepository,
DisplayController displayController,
- ShellTaskOrganizer shellTaskOrganizer) {
+ ShellTaskOrganizer shellTaskOrganizer,
+ ShellCommandHandler shellCommandHandler) {
if (DesktopModeStatus.canEnterDesktopMode(context)) {
return Optional.of(
new DesktopImmersiveController(
- transitions, desktopRepository, displayController, shellTaskOrganizer));
+ shellInit,
+ transitions,
+ desktopRepository,
+ displayController,
+ shellTaskOrganizer,
+ shellCommandHandler));
}
return Optional.empty();
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java
index 3a4764d45f2c..3cd5df3121c1 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip1Module.java
@@ -19,6 +19,7 @@ package com.android.wm.shell.dagger.pip;
import android.content.Context;
import android.os.Handler;
+import com.android.wm.shell.RootTaskDisplayAreaOrganizer;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.WindowManagerShellWrapper;
import com.android.wm.shell.common.DisplayController;
@@ -41,6 +42,7 @@ import com.android.wm.shell.common.pip.PipUiEventLogger;
import com.android.wm.shell.common.pip.SizeSpecSource;
import com.android.wm.shell.dagger.WMShellBaseModule;
import com.android.wm.shell.dagger.WMSingleton;
+import com.android.wm.shell.desktopmode.DesktopRepository;
import com.android.wm.shell.onehanded.OneHandedController;
import com.android.wm.shell.pip.PipAnimationController;
import com.android.wm.shell.pip.PipParamsChangedForwarder;
@@ -169,6 +171,8 @@ public abstract class Pip1Module {
PipParamsChangedForwarder pipParamsChangedForwarder,
Optional<SplitScreenController> splitScreenControllerOptional,
Optional<PipPerfHintController> pipPerfHintControllerOptional,
+ Optional<DesktopRepository> desktopRepositoryOptional,
+ RootTaskDisplayAreaOrganizer rootTaskDisplayAreaOrganizer,
DisplayController displayController,
PipUiEventLogger pipUiEventLogger, ShellTaskOrganizer shellTaskOrganizer,
@ShellMainThread ShellExecutor mainExecutor) {
@@ -176,7 +180,8 @@ public abstract class Pip1Module {
syncTransactionQueue, pipTransitionState, pipBoundsState, pipDisplayLayoutState,
pipBoundsAlgorithm, menuPhoneController, pipAnimationController,
pipSurfaceTransactionHelper, pipTransitionController, pipParamsChangedForwarder,
- splitScreenControllerOptional, pipPerfHintControllerOptional, displayController,
+ splitScreenControllerOptional, pipPerfHintControllerOptional,
+ desktopRepositoryOptional, rootTaskDisplayAreaOrganizer, displayController,
pipUiEventLogger, shellTaskOrganizer, mainExecutor);
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java
index 8d1b15c1e631..78e676f8cd45 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/TvPipModule.java
@@ -22,6 +22,7 @@ import android.os.SystemClock;
import androidx.annotation.NonNull;
+import com.android.wm.shell.RootTaskDisplayAreaOrganizer;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.WindowManagerShellWrapper;
import com.android.wm.shell.common.DisplayController;
@@ -214,6 +215,7 @@ public abstract class TvPipModule {
PipSurfaceTransactionHelper pipSurfaceTransactionHelper,
Optional<SplitScreenController> splitScreenControllerOptional,
Optional<PipPerfHintController> pipPerfHintControllerOptional,
+ RootTaskDisplayAreaOrganizer rootTaskDisplayAreaOrganizer,
DisplayController displayController,
PipUiEventLogger pipUiEventLogger, ShellTaskOrganizer shellTaskOrganizer,
@ShellMainThread ShellExecutor mainExecutor) {
@@ -221,8 +223,9 @@ public abstract class TvPipModule {
syncTransactionQueue, pipTransitionState, tvPipBoundsState, pipDisplayLayoutState,
tvPipBoundsAlgorithm, tvPipMenuController, pipAnimationController,
pipSurfaceTransactionHelper, tvPipTransition, pipParamsChangedForwarder,
- splitScreenControllerOptional, pipPerfHintControllerOptional, displayController,
- pipUiEventLogger, shellTaskOrganizer, mainExecutor);
+ splitScreenControllerOptional, pipPerfHintControllerOptional,
+ rootTaskDisplayAreaOrganizer, displayController, pipUiEventLogger,
+ shellTaskOrganizer, mainExecutor);
}
@WMSingleton
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopImmersiveController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopImmersiveController.kt
index f69aa6df6a1d..1acde73e68dc 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopImmersiveController.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopImmersiveController.kt
@@ -34,10 +34,13 @@ import com.android.window.flags.Flags
import com.android.wm.shell.ShellTaskOrganizer
import com.android.wm.shell.common.DisplayController
import com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_DESKTOP_MODE
+import com.android.wm.shell.sysui.ShellCommandHandler
+import com.android.wm.shell.sysui.ShellInit
import com.android.wm.shell.transition.Transitions
import com.android.wm.shell.transition.Transitions.TransitionHandler
import com.android.wm.shell.transition.Transitions.TransitionObserver
import com.android.wm.shell.windowdecor.OnTaskResizeAnimationListener
+import java.io.PrintWriter
/**
* A controller to move tasks in/out of desktop's full immersive state where the task
@@ -45,27 +48,34 @@ import com.android.wm.shell.windowdecor.OnTaskResizeAnimationListener
* be transient below the status bar like in fullscreen immersive mode.
*/
class DesktopImmersiveController(
+ shellInit: ShellInit,
private val transitions: Transitions,
private val desktopRepository: DesktopRepository,
private val displayController: DisplayController,
private val shellTaskOrganizer: ShellTaskOrganizer,
+ private val shellCommandHandler: ShellCommandHandler,
private val transactionSupplier: () -> SurfaceControl.Transaction,
) : TransitionHandler, TransitionObserver {
constructor(
+ shellInit: ShellInit,
transitions: Transitions,
desktopRepository: DesktopRepository,
displayController: DisplayController,
shellTaskOrganizer: ShellTaskOrganizer,
+ shellCommandHandler: ShellCommandHandler,
) : this(
+ shellInit,
transitions,
desktopRepository,
displayController,
shellTaskOrganizer,
+ shellCommandHandler,
{ SurfaceControl.Transaction() }
)
- private var state: TransitionState? = null
+ @VisibleForTesting
+ var state: TransitionState? = null
@VisibleForTesting
val pendingExternalExitTransitions = mutableListOf<ExternalPendingExit>()
@@ -79,10 +89,21 @@ class DesktopImmersiveController(
/** A listener to invoke on animation changes during entry/exit. */
var onTaskResizeAnimationListener: OnTaskResizeAnimationListener? = null
+ init {
+ shellInit.addInitCallback({ onInit() }, this)
+ }
+
+ fun onInit() {
+ shellCommandHandler.addDumpCallback(this::dump, this)
+ }
+
/** Starts a transition to enter full immersive state inside the desktop. */
fun moveTaskToImmersive(taskInfo: RunningTaskInfo) {
if (inProgress) {
- logV("Cannot start entry because transition already in progress.")
+ logV(
+ "Cannot start entry because transition(s) already in progress: %s",
+ getRunningTransitions()
+ )
return
}
val wct = WindowContainerTransaction().apply {
@@ -100,7 +121,10 @@ class DesktopImmersiveController(
fun moveTaskToNonImmersive(taskInfo: RunningTaskInfo) {
if (inProgress) {
- logV("Cannot start exit because transition already in progress.")
+ logV(
+ "Cannot start exit because transition(s) already in progress: %s",
+ getRunningTransitions()
+ )
return
}
@@ -225,14 +249,19 @@ class DesktopImmersiveController(
finishCallback: Transitions.TransitionFinishCallback
): Boolean {
val state = requireState()
- if (transition != state.transition) return false
+ check(state.transition == transition) {
+ "Transition $transition did not match expected state=$state"
+ }
logD("startAnimation transition=%s", transition)
animateResize(
targetTaskId = state.taskId,
info = info,
startTransaction = startTransaction,
finishTransaction = finishTransaction,
- finishCallback = finishCallback
+ finishCallback = {
+ finishCallback.onTransitionFinished(/* wct= */ null)
+ clearState()
+ },
)
return true
}
@@ -242,12 +271,18 @@ class DesktopImmersiveController(
info: TransitionInfo,
startTransaction: SurfaceControl.Transaction,
finishTransaction: SurfaceControl.Transaction,
- finishCallback: Transitions.TransitionFinishCallback
+ finishCallback: Transitions.TransitionFinishCallback,
) {
logD("animateResize for task#%d", targetTaskId)
- val change = info.changes.first { c ->
+ val change = info.changes.firstOrNull { c ->
val taskInfo = c.taskInfo
- return@first taskInfo != null && taskInfo.taskId == targetTaskId
+ return@firstOrNull taskInfo != null && taskInfo.taskId == targetTaskId
+ }
+ if (change == null) {
+ logD("Did not find change for task#%d to animate", targetTaskId)
+ startTransaction.apply()
+ finishCallback.onTransitionFinished(/* wct= */ null)
+ return
}
animateResizeChange(change, startTransaction, finishTransaction, finishCallback)
}
@@ -288,7 +323,6 @@ class DesktopImmersiveController(
.apply()
onTaskResizeAnimationListener?.onAnimationEnd(taskId)
finishCallback.onTransitionFinished(null /* wct */)
- clearState()
}
)
addUpdateListener { animation ->
@@ -357,8 +391,17 @@ class DesktopImmersiveController(
// Check if this is a direct immersive enter/exit transition.
if (transition == state?.transition) {
val state = requireState()
- val startBounds = info.changes.first { c -> c.taskInfo?.taskId == state.taskId }
- .startAbsBounds
+ val immersiveChange = info.changes.firstOrNull { c ->
+ c.taskInfo?.taskId == state.taskId
+ }
+ if (immersiveChange == null) {
+ logV(
+ "Direct move for task#%d in %s direction missing immersive change.",
+ state.taskId, state.direction
+ )
+ return
+ }
+ val startBounds = immersiveChange.startAbsBounds
logV("Direct move for task#%d in %s direction verified", state.taskId, state.direction)
when (state.direction) {
Direction.ENTER -> {
@@ -446,11 +489,30 @@ class DesktopImmersiveController(
private fun requireState(): TransitionState =
state ?: error("Expected non-null transition state")
+ private fun getRunningTransitions(): List<IBinder> {
+ val running = mutableListOf<IBinder>()
+ state?.let {
+ running.add(it.transition)
+ }
+ pendingExternalExitTransitions.forEach {
+ running.add(it.transition)
+ }
+ return running
+ }
+
private fun TransitionInfo.hasTaskChange(taskId: Int): Boolean =
changes.any { c -> c.taskInfo?.taskId == taskId }
+ private fun dump(pw: PrintWriter, prefix: String) {
+ val innerPrefix = "$prefix "
+ pw.println("${prefix}DesktopImmersiveController")
+ pw.println(innerPrefix + "state=" + state)
+ pw.println(innerPrefix + "pendingExternalExitTransitions=" + pendingExternalExitTransitions)
+ }
+
/** The state of the currently running transition. */
- private data class TransitionState(
+ @VisibleForTesting
+ data class TransitionState(
val transition: IBinder,
val displayId: Int,
val taskId: Int,
@@ -483,7 +545,8 @@ class DesktopImmersiveController(
fun asExit(): Exit? = if (this is Exit) this else null
}
- private enum class Direction {
+ @VisibleForTesting
+ enum class Direction {
ENTER, EXIT
}
@@ -495,9 +558,10 @@ class DesktopImmersiveController(
ProtoLog.d(WM_SHELL_DESKTOP_MODE, "%s: $msg", TAG, *arguments)
}
- private companion object {
+ companion object {
private const val TAG = "DesktopImmersive"
- private const val FULL_IMMERSIVE_ANIM_DURATION_MS = 336L
+ @VisibleForTesting
+ const val FULL_IMMERSIVE_ANIM_DURATION_MS = 336L
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt
index fda709a4a2d7..08ca55f93e3f 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopRepository.kt
@@ -102,6 +102,9 @@ class DesktopRepository (
/* Tracks last bounds of task before toggled to stable bounds. */
private val boundsBeforeMaximizeByTaskId = SparseArray<Rect>()
+ /* Tracks last bounds of task before it is minimized. */
+ private val boundsBeforeMinimizeByTaskId = SparseArray<Rect>()
+
/* Tracks last bounds of task before toggled to immersive state. */
private val boundsBeforeFullImmersiveByTaskId = SparseArray<Rect>()
@@ -462,6 +465,14 @@ class DesktopRepository (
fun saveBoundsBeforeMaximize(taskId: Int, bounds: Rect) =
boundsBeforeMaximizeByTaskId.set(taskId, Rect(bounds))
+ /** Removes and returns the bounds saved before minimizing the given task. */
+ fun removeBoundsBeforeMinimize(taskId: Int): Rect? =
+ boundsBeforeMinimizeByTaskId.removeReturnOld(taskId)
+
+ /** Saves the bounds of the given task before minimizing. */
+ fun saveBoundsBeforeMinimize(taskId: Int, bounds: Rect?) =
+ boundsBeforeMinimizeByTaskId.set(taskId, Rect(bounds))
+
/** Removes and returns the bounds saved before entering immersive with the given task. */
fun removeBoundsBeforeFullImmersive(taskId: Int): Rect? =
boundsBeforeFullImmersiveByTaskId.removeReturnOld(taskId)
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
index 162879c97a16..927fd88fb4ff 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
@@ -1770,9 +1770,13 @@ class DesktopTasksController(
transition: IBinder,
taskIdToMinimize: Int,
) {
- val taskToMinimize = shellTaskOrganizer.getRunningTaskInfo(taskIdToMinimize) ?: return
+ val taskToMinimize = shellTaskOrganizer.getRunningTaskInfo(taskIdToMinimize)
desktopTasksLimiter.ifPresent {
- it.addPendingMinimizeChange(transition, taskToMinimize.displayId, taskToMinimize.taskId)
+ it.addPendingMinimizeChange(
+ transition = transition,
+ displayId = taskToMinimize?.displayId ?: DEFAULT_DISPLAY,
+ taskId = taskIdToMinimize
+ )
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksLimiter.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksLimiter.kt
index f0e3a2bd8ffc..77af627a948a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksLimiter.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksLimiter.kt
@@ -92,6 +92,12 @@ class DesktopTasksLimiter (
}
taskToMinimize.transitionInfo = info
activeTransitionTokensAndTasks[transition] = taskToMinimize
+
+ // Save current bounds before minimizing in case we need to restore to it later.
+ val boundsBeforeMinimize = info.changes.find { change ->
+ change.taskInfo?.taskId == taskToMinimize.taskId }?.startAbsBounds
+ taskRepository.saveBoundsBeforeMinimize(taskToMinimize.taskId, boundsBeforeMinimize)
+
this@DesktopTasksLimiter.minimizeTask(
taskToMinimize.displayId, taskToMinimize.taskId)
}
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 c4e63dfdade9..86c826a680f6 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
@@ -17,6 +17,7 @@
package com.android.wm.shell.pip;
import static android.app.ActivityTaskManager.INVALID_TASK_ID;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
@@ -67,6 +68,7 @@ import android.view.Choreographer;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceControl;
+import android.window.DisplayAreaInfo;
import android.window.TaskOrganizer;
import android.window.TaskSnapshot;
import android.window.WindowContainerToken;
@@ -74,7 +76,9 @@ import android.window.WindowContainerTransaction;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.protolog.ProtoLog;
+import com.android.window.flags.Flags;
import com.android.wm.shell.R;
+import com.android.wm.shell.RootTaskDisplayAreaOrganizer;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.common.DisplayController;
import com.android.wm.shell.common.ScreenshotUtils;
@@ -87,6 +91,7 @@ import com.android.wm.shell.common.pip.PipMenuController;
import com.android.wm.shell.common.pip.PipPerfHintController;
import com.android.wm.shell.common.pip.PipUiEventLogger;
import com.android.wm.shell.common.pip.PipUtils;
+import com.android.wm.shell.desktopmode.DesktopRepository;
import com.android.wm.shell.pip.phone.PipMotionHelper;
import com.android.wm.shell.protolog.ShellProtoLogGroup;
import com.android.wm.shell.shared.animation.Interpolators;
@@ -145,6 +150,8 @@ public class PipTaskOrganizer implements ShellTaskOrganizer.TaskListener,
private final PipSurfaceTransactionHelper mSurfaceTransactionHelper;
private final Optional<SplitScreenController> mSplitScreenOptional;
@Nullable private final PipPerfHintController mPipPerfHintController;
+ private final Optional<DesktopRepository> mDesktopRepositoryOptional;
+ private final RootTaskDisplayAreaOrganizer mRootTaskDisplayAreaOrganizer;
protected final ShellTaskOrganizer mTaskOrganizer;
protected final ShellExecutor mMainExecutor;
@@ -388,6 +395,8 @@ public class PipTaskOrganizer implements ShellTaskOrganizer.TaskListener,
@NonNull PipParamsChangedForwarder pipParamsChangedForwarder,
Optional<SplitScreenController> splitScreenOptional,
Optional<PipPerfHintController> pipPerfHintControllerOptional,
+ Optional<DesktopRepository> desktopRepositoryOptional,
+ RootTaskDisplayAreaOrganizer rootTaskDisplayAreaOrganizer,
@NonNull DisplayController displayController,
@NonNull PipUiEventLogger pipUiEventLogger,
@NonNull ShellTaskOrganizer shellTaskOrganizer,
@@ -414,6 +423,8 @@ public class PipTaskOrganizer implements ShellTaskOrganizer.TaskListener,
new PipSurfaceTransactionHelper.VsyncSurfaceControlTransactionFactory();
mSplitScreenOptional = splitScreenOptional;
mPipPerfHintController = pipPerfHintControllerOptional.orElse(null);
+ mDesktopRepositoryOptional = desktopRepositoryOptional;
+ mRootTaskDisplayAreaOrganizer = rootTaskDisplayAreaOrganizer;
mTaskOrganizer = shellTaskOrganizer;
mMainExecutor = mainExecutor;
@@ -741,10 +752,23 @@ public class PipTaskOrganizer implements ShellTaskOrganizer.TaskListener,
}
/** Returns the bounds to restore to when exiting PIP mode. */
+ // TODO(b/377581840): Instead of manually tracking bounds, use bounds from Core.
public Rect getExitDestinationBounds() {
+ if (isPipLaunchedInDesktopMode()) {
+ final Rect freeformBounds = mDesktopRepositoryOptional.get().removeBoundsBeforeMinimize(
+ mTaskInfo.taskId);
+ return Objects.requireNonNullElseGet(freeformBounds, mPipBoundsState::getDisplayBounds);
+ }
return mPipBoundsState.getDisplayBounds();
}
+ /** Returns whether PiP was launched while in desktop mode. */
+ // TODO(377581840): Update this check to include non-minimized cases, e.g. split to PiP etc.
+ private boolean isPipLaunchedInDesktopMode() {
+ return Flags.enableDesktopWindowingPip() && mDesktopRepositoryOptional.isPresent()
+ && mDesktopRepositoryOptional.get().isMinimizedTask(mTaskInfo.taskId);
+ }
+
private void exitLaunchIntoPipTask(WindowContainerTransaction wct) {
wct.startTask(mTaskInfo.launchIntoPipHostTaskId, null /* ActivityOptions */);
mTaskOrganizer.applyTransaction(wct);
@@ -1808,7 +1832,25 @@ public class PipTaskOrganizer implements ShellTaskOrganizer.TaskListener,
* and can be overridden to restore to an alternate windowing mode.
*/
public int getOutPipWindowingMode() {
- // By default, simply reset the windowing mode to undefined.
+ final DisplayAreaInfo tdaInfo = mRootTaskDisplayAreaOrganizer.getDisplayAreaInfo(
+ mTaskInfo.displayId);
+
+ // If PiP was launched while in desktop mode (we should return the task to freeform
+ // windowing mode):
+ // 1) If the display windowing mode is freeform, set windowing mode to undefined so it will
+ // resolve the windowing mode to the display's windowing mode.
+ // 2) If the display windowing mode is not freeform, set windowing mode to freeform.
+ if (tdaInfo != null && isPipLaunchedInDesktopMode()) {
+ final int displayWindowingMode =
+ tdaInfo.configuration.windowConfiguration.getWindowingMode();
+ if (displayWindowingMode == WINDOWING_MODE_FREEFORM) {
+ return WINDOWING_MODE_UNDEFINED;
+ } else {
+ return WINDOWING_MODE_FREEFORM;
+ }
+ }
+
+ // By default, or if the task is going to fullscreen, reset the windowing mode to undefined.
return WINDOWING_MODE_UNDEFINED;
}
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 28b91c6cb812..8220ea5ea575 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
@@ -530,6 +530,13 @@ public class PipTransition extends PipTransitionController {
if (mFixedRotationState != FIXED_ROTATION_TRANSITION
&& mFinishTransaction != null) {
mFinishTransaction.merge(tx);
+ // Set window crop and position to destination bounds to avoid flickering.
+ if (hasValidLeash) {
+ mFinishTransaction.setWindowCrop(leash, destinationBounds.width(),
+ destinationBounds.height());
+ mFinishTransaction.setPosition(leash, destinationBounds.left,
+ destinationBounds.top);
+ }
}
} else {
wct = new WindowContainerTransaction();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipTaskOrganizer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipTaskOrganizer.java
index 614ef2ab9831..fcba46108f67 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipTaskOrganizer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipTaskOrganizer.java
@@ -21,6 +21,7 @@ import android.content.Context;
import androidx.annotation.NonNull;
+import com.android.wm.shell.RootTaskDisplayAreaOrganizer;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.common.DisplayController;
import com.android.wm.shell.common.ShellExecutor;
@@ -61,6 +62,7 @@ public class TvPipTaskOrganizer extends PipTaskOrganizer {
@NonNull PipParamsChangedForwarder pipParamsChangedForwarder,
Optional<SplitScreenController> splitScreenOptional,
Optional<PipPerfHintController> pipPerfHintControllerOptional,
+ @NonNull RootTaskDisplayAreaOrganizer rootTaskDisplayAreaOrganizer,
@NonNull DisplayController displayController,
@NonNull PipUiEventLogger pipUiEventLogger,
@NonNull ShellTaskOrganizer shellTaskOrganizer,
@@ -68,8 +70,9 @@ public class TvPipTaskOrganizer extends PipTaskOrganizer {
super(context, syncTransactionQueue, pipTransitionState, pipBoundsState,
pipDisplayLayoutState, boundsHandler, pipMenuController, pipAnimationController,
surfaceTransactionHelper, tvPipTransition, pipParamsChangedForwarder,
- splitScreenOptional, pipPerfHintControllerOptional, displayController,
- pipUiEventLogger, shellTaskOrganizer, mainExecutor);
+ splitScreenOptional, pipPerfHintControllerOptional, Optional.empty(),
+ rootTaskDisplayAreaOrganizer, displayController, pipUiEventLogger,
+ shellTaskOrganizer, mainExecutor);
mTvPipTransition = tvPipTransition;
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java
index ea783e9cadb6..3caad0966b1f 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java
@@ -20,6 +20,7 @@ import static android.app.WindowConfiguration.ROTATION_UNDEFINED;
import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.view.Surface.ROTATION_0;
import static android.view.Surface.ROTATION_270;
+import static android.view.Surface.ROTATION_90;
import static android.view.WindowManager.TRANSIT_CLOSE;
import static android.view.WindowManager.TRANSIT_OPEN;
import static android.view.WindowManager.TRANSIT_PIP;
@@ -230,6 +231,11 @@ public class PipTransition extends PipTransitionController implements
// If there is no PiP change, exit this transition handler and potentially try others.
if (pipChange == null) return false;
+ // Other targets might have default transforms applied that are not relevant when
+ // playing PiP transitions, so reset those transforms if needed.
+ prepareOtherTargetTransforms(info, startTransaction, finishTransaction);
+
+ // Update the PipTransitionState while supplying the PiP leash and token to be cached.
Bundle extra = new Bundle();
extra.putParcelable(PIP_TASK_TOKEN, pipChange.getContainer());
extra.putParcelable(PIP_TASK_LEASH, pipChange.getLeash());
@@ -341,17 +347,21 @@ public class PipTransition extends PipTransitionController implements
(destinationBounds.height() - overlaySize) / 2f);
}
- final int startRotation = pipChange.getStartRotation();
- final int endRotation = mPipDisplayLayoutState.getRotation();
- final int delta = endRotation == ROTATION_UNDEFINED ? ROTATION_0
- : startRotation - endRotation;
+ final int delta = getFixedRotationDelta(info, pipChange);
if (delta != ROTATION_0) {
- mPipTransitionState.setInFixedRotation(true);
- handleBoundsEnterFixedRotation(pipChange, pipActivityChange, endRotation);
+ // Update transition target changes in place to prepare for fixed rotation.
+ handleBoundsEnterFixedRotation(info, pipChange, pipActivityChange);
}
+ // Update the src-rect-hint in params in place, to set up initial animator transform.
+ Rect sourceRectHint = getAdjustedSourceRectHint(info, pipChange, pipActivityChange);
+ pipChange.getTaskInfo().pictureInPictureParams.getSourceRectHint().set(sourceRectHint);
+
+ // Config-at-end transitions need to have their activities transformed before starting
+ // the animation; this makes the buffer seem like it's been updated to final size.
prepareConfigAtEndActivity(startTransaction, finishTransaction, pipChange,
pipActivityChange);
+
startTransaction.merge(finishTransaction);
PipEnterAnimator animator = new PipEnterAnimator(mContext, pipLeash,
startTransaction, finishTransaction, destinationBounds, delta);
@@ -387,55 +397,36 @@ public class PipTransition extends PipTransitionController implements
return false;
}
+ final SurfaceControl pipLeash = getLeash(pipChange);
final Rect startBounds = pipChange.getStartAbsBounds();
final Rect endBounds = pipChange.getEndAbsBounds();
-
final PictureInPictureParams params = pipChange.getTaskInfo().pictureInPictureParams;
- final float aspectRatio = mPipBoundsAlgorithm.getAspectRatioOrDefault(params);
- final Rect sourceRectHint = PipBoundsAlgorithm.getValidSourceHintRect(params, startBounds,
- endBounds);
- final Rect adjustedSourceRectHint = sourceRectHint != null ? new Rect(sourceRectHint)
- : PipUtils.getEnterPipWithOverlaySrcRectHint(startBounds, aspectRatio);
-
- final SurfaceControl pipLeash = mPipTransitionState.getPinnedTaskLeash();
-
- // For opening type transitions, if there is a change of mode TO_FRONT/OPEN,
- // make sure that change has alpha of 1f, since it's init state might be set to alpha=0f
- // by the Transitions framework to simplify Task opening transitions.
- if (TransitionUtil.isOpeningType(info.getType())) {
- for (TransitionInfo.Change change : info.getChanges()) {
- if (change.getLeash() == null) continue;
- if (change.getMode() == TRANSIT_OPEN || change.getMode() == TRANSIT_TO_FRONT) {
- startTransaction.setAlpha(change.getLeash(), 1f);
- }
- }
- }
-
- final TransitionInfo.Change fixedRotationChange = findFixedRotationChange(info);
- final int startRotation = pipChange.getStartRotation();
- final int endRotation = fixedRotationChange != null
- ? fixedRotationChange.getEndFixedRotation() : ROTATION_UNDEFINED;
- final int delta = endRotation == ROTATION_UNDEFINED ? ROTATION_0
- : startRotation - endRotation;
+ final Rect adjustedSourceRectHint = getAdjustedSourceRectHint(info, pipChange,
+ pipActivityChange);
+ final int delta = getFixedRotationDelta(info, pipChange);
if (delta != ROTATION_0) {
- mPipTransitionState.setInFixedRotation(true);
- handleBoundsEnterFixedRotation(pipChange, pipActivityChange,
- fixedRotationChange.getEndFixedRotation());
+ // Update transition target changes in place to prepare for fixed rotation.
+ handleBoundsEnterFixedRotation(info, pipChange, pipActivityChange);
}
PipEnterAnimator animator = new PipEnterAnimator(mContext, pipLeash,
startTransaction, finishTransaction, endBounds, delta);
- if (sourceRectHint == null) {
- // update the src-rect-hint in params in place, to set up initial animator transform.
- params.getSourceRectHint().set(adjustedSourceRectHint);
+ if (PipBoundsAlgorithm.getValidSourceHintRect(params, startBounds, endBounds) == null) {
+ // If app provided src-rect-hint is invalid, use app icon overlay.
animator.setAppIconContentOverlay(
mContext, startBounds, endBounds, pipChange.getTaskInfo().topActivityInfo,
mPipBoundsState.getLauncherState().getAppIconSizePx());
}
+ // Update the src-rect-hint in params in place, to set up initial animator transform.
+ params.getSourceRectHint().set(adjustedSourceRectHint);
+
+ // Config-at-end transitions need to have their activities transformed before starting
+ // the animation; this makes the buffer seem like it's been updated to final size.
prepareConfigAtEndActivity(startTransaction, finishTransaction, pipChange,
pipActivityChange);
+
animator.setAnimationStartCallback(() -> animator.setEnterStartState(pipChange));
animator.setAnimationEndCallback(() -> {
if (animator.getContentOverlayLeash() != null) {
@@ -457,11 +448,22 @@ public class PipTransition extends PipTransitionController implements
animator.start();
}
- private void handleBoundsEnterFixedRotation(TransitionInfo.Change pipTaskChange,
- TransitionInfo.Change pipActivityChange, int endRotation) {
- final Rect endBounds = pipTaskChange.getEndAbsBounds();
- final Rect endActivityBounds = pipActivityChange.getEndAbsBounds();
- int startRotation = pipTaskChange.getStartRotation();
+ private void handleBoundsEnterFixedRotation(TransitionInfo info,
+ TransitionInfo.Change outPipTaskChange,
+ TransitionInfo.Change outPipActivityChange) {
+ final TransitionInfo.Change fixedRotationChange = findFixedRotationChange(info);
+ final Rect endBounds = outPipTaskChange.getEndAbsBounds();
+ final Rect endActivityBounds = outPipActivityChange.getEndAbsBounds();
+ int startRotation = outPipTaskChange.getStartRotation();
+ int endRotation = fixedRotationChange != null
+ ? fixedRotationChange.getEndFixedRotation() : mPipDisplayLayoutState.getRotation();
+
+ if (startRotation == endRotation) {
+ return;
+ }
+
+ // This is used by display change listeners to respond properly to fixed rotation.
+ mPipTransitionState.setInFixedRotation(true);
// Cache the task to activity offset to potentially restore later.
Point activityEndOffset = new Point(endActivityBounds.left - endBounds.left,
@@ -490,15 +492,15 @@ public class PipTransition extends PipTransitionController implements
endBounds.top + activityEndOffset.y);
}
- private void handleExpandFixedRotation(TransitionInfo.Change pipTaskChange, int endRotation) {
- final Rect endBounds = pipTaskChange.getEndAbsBounds();
+ private void handleExpandFixedRotation(TransitionInfo.Change outPipTaskChange, int delta) {
+ final Rect endBounds = outPipTaskChange.getEndAbsBounds();
final int width = endBounds.width();
final int height = endBounds.height();
final int left = endBounds.left;
final int top = endBounds.top;
int newTop, newLeft;
- if (endRotation == Surface.ROTATION_90) {
+ if (delta == Surface.ROTATION_90) {
newLeft = top;
newTop = -(left + width);
} else {
@@ -585,15 +587,11 @@ public class PipTransition extends PipTransitionController implements
final Rect sourceRectHint = PipBoundsAlgorithm.getValidSourceHintRect(params, endBounds,
startBounds);
- final TransitionInfo.Change fixedRotationChange = findFixedRotationChange(info);
- final int startRotation = pipChange.getStartRotation();
- final int endRotation = fixedRotationChange != null
- ? fixedRotationChange.getEndFixedRotation() : ROTATION_UNDEFINED;
- final int delta = endRotation == ROTATION_UNDEFINED ? ROTATION_0
- : endRotation - startRotation;
-
+ // We define delta = startRotation - endRotation, so we need to flip the sign.
+ final int delta = -getFixedRotationDelta(info, pipChange);
if (delta != ROTATION_0) {
- handleExpandFixedRotation(pipChange, endRotation);
+ // Update PiP target change in place to prepare for fixed rotation;
+ handleExpandFixedRotation(pipChange, delta);
}
PipExpandAnimator animator = new PipExpandAnimator(mContext, pipLeash,
@@ -661,6 +659,72 @@ public class PipTransition extends PipTransitionController implements
return null;
}
+ @NonNull
+ private Rect getAdjustedSourceRectHint(@NonNull TransitionInfo info,
+ @NonNull TransitionInfo.Change pipTaskChange,
+ @NonNull TransitionInfo.Change pipActivityChange) {
+ final Rect startBounds = pipTaskChange.getStartAbsBounds();
+ final Rect endBounds = pipTaskChange.getEndAbsBounds();
+ final PictureInPictureParams params = pipTaskChange.getTaskInfo().pictureInPictureParams;
+
+ // Get the source-rect-hint provided by the app and check its validity; null if invalid.
+ final Rect sourceRectHint = PipBoundsAlgorithm.getValidSourceHintRect(params, startBounds,
+ endBounds);
+
+ final Rect adjustedSourceRectHint = new Rect();
+ if (sourceRectHint != null) {
+ adjustedSourceRectHint.set(sourceRectHint);
+ // If multi-activity PiP, use the parent task before PiP to retrieve display cutouts;
+ // then, offset the valid app provided source rect hint by the cutout insets.
+ // For single-activity PiP, just use the pinned task to get the cutouts instead.
+ TransitionInfo.Change parentBeforePip = pipActivityChange.getLastParent() != null
+ ? getChangeByToken(info, pipActivityChange.getLastParent()) : null;
+ Rect cutoutInsets = parentBeforePip != null
+ ? parentBeforePip.getTaskInfo().displayCutoutInsets
+ : pipTaskChange.getTaskInfo().displayCutoutInsets;
+ if (cutoutInsets != null
+ && getFixedRotationDelta(info, pipTaskChange) == ROTATION_90) {
+ adjustedSourceRectHint.offset(cutoutInsets.left, cutoutInsets.top);
+ }
+ } else {
+ // For non-valid app provided src-rect-hint, calculate one to crop into during
+ // app icon overlay animation.
+ float aspectRatio = mPipBoundsAlgorithm.getAspectRatioOrDefault(params);
+ adjustedSourceRectHint.set(
+ PipUtils.getEnterPipWithOverlaySrcRectHint(startBounds, aspectRatio));
+ }
+ return adjustedSourceRectHint;
+ }
+
+ @Surface.Rotation
+ private int getFixedRotationDelta(@NonNull TransitionInfo info,
+ @NonNull TransitionInfo.Change pipChange) {
+ TransitionInfo.Change fixedRotationChange = findFixedRotationChange(info);
+ int startRotation = pipChange.getStartRotation();
+ int endRotation = fixedRotationChange != null
+ ? fixedRotationChange.getEndFixedRotation() : mPipDisplayLayoutState.getRotation();
+ int delta = endRotation == ROTATION_UNDEFINED ? ROTATION_0
+ : startRotation - endRotation;
+ return delta;
+ }
+
+ private void prepareOtherTargetTransforms(TransitionInfo info,
+ SurfaceControl.Transaction startTransaction,
+ SurfaceControl.Transaction finishTransaction) {
+ // For opening type transitions, if there is a change of mode TO_FRONT/OPEN,
+ // make sure that change has alpha of 1f, since it's init state might be set to alpha=0f
+ // by the Transitions framework to simplify Task opening transitions.
+ if (TransitionUtil.isOpeningType(info.getType())) {
+ for (TransitionInfo.Change change : info.getChanges()) {
+ if (change.getLeash() == null) continue;
+ if (change.getMode() == TRANSIT_OPEN || change.getMode() == TRANSIT_TO_FRONT) {
+ startTransaction.setAlpha(change.getLeash(), 1f);
+ }
+ }
+ }
+
+ }
+
private WindowContainerTransaction getEnterPipTransaction(@NonNull IBinder transition,
@NonNull TransitionRequestInfo request) {
// cache the original task token to check for multi-activity case later
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentsTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentsTransitionHandler.java
index 40065b9287a6..9016c45e8197 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentsTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentsTransitionHandler.java
@@ -34,6 +34,8 @@ import static android.window.TransitionInfo.FLAG_TRANSLUCENT;
import static com.android.wm.shell.shared.ShellSharedConstants.KEY_EXTRA_SHELL_CAN_HAND_OFF_ANIMATION;
import static com.android.wm.shell.shared.split.SplitBounds.KEY_EXTRA_SPLIT_BOUNDS;
+import static com.android.wm.shell.transition.Transitions.TRANSIT_END_RECENTS_TRANSITION;
+import static com.android.wm.shell.transition.Transitions.TRANSIT_START_RECENTS_TRANSITION;
import android.annotation.Nullable;
import android.annotation.SuppressLint;
@@ -67,6 +69,7 @@ import androidx.annotation.NonNull;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.os.IResultReceiver;
import com.android.internal.protolog.ProtoLog;
+import com.android.wm.shell.Flags;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.common.ShellExecutor;
import com.android.wm.shell.common.pip.PipUtils;
@@ -216,8 +219,11 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
break;
}
}
- final IBinder transition = mTransitions.startTransition(TRANSIT_TO_FRONT, wct,
- mixer == null ? this : mixer);
+ final int transitionType = Flags.enableShellTopTaskTracking()
+ ? TRANSIT_START_RECENTS_TRANSITION
+ : TRANSIT_TO_FRONT;
+ final IBinder transition = mTransitions.startTransition(transitionType,
+ wct, mixer == null ? this : mixer);
if (mixer != null) {
setTransitionForMixer.accept(transition);
}
@@ -300,7 +306,7 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
"RecentsTransitionHandler.mergeAnimation: no controller found");
return;
}
- controller.merge(info, t, finishCallback);
+ controller.merge(info, t, mergeTarget, finishCallback);
}
@Override
@@ -367,6 +373,8 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
private boolean mPausingSeparateHome = false;
private ArrayMap<SurfaceControl, SurfaceControl> mLeashMap = null;
private PictureInPictureSurfaceTransaction mPipTransaction = null;
+ // This is the transition that backs the entire recents transition, and the one that the
+ // pending finish transition below will be merged into
private IBinder mTransition = null;
private boolean mKeyguardLocked = false;
private boolean mWillFinishToHome = false;
@@ -386,6 +394,10 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
// next called.
private Pair<int[], TaskSnapshot[]> mPendingPauseSnapshotsForCancel;
+ // Used to track a pending finish transition
+ private IBinder mPendingFinishTransition;
+ private IResultReceiver mPendingRunnerFinishCb;
+
RecentsController(IRecentsAnimationRunner listener) {
mInstanceId = System.identityHashCode(this);
mListener = listener;
@@ -523,6 +535,11 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
mInfo = null;
mTransition = null;
mPendingPauseSnapshotsForCancel = null;
+ mPipTaskId = -1;
+ mPipTask = null;
+ mPipTransaction = null;
+ mPendingRunnerFinishCb = null;
+ mPendingFinishTransition = null;
mControllers.remove(this);
for (int i = 0; i < mStateListeners.size(); i++) {
mStateListeners.get(i).onAnimationStateChanged(false);
@@ -734,6 +751,8 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
// the pausing apps.
t.setLayer(target.leash, layer);
} else if (taskInfo != null && taskInfo.topActivityType == ACTIVITY_TYPE_HOME) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
+ " not handling home taskId=%d", taskInfo.taskId);
// do nothing
} else if (TransitionUtil.isOpeningType(change.getMode())) {
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
@@ -872,16 +891,35 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
}
}
+ /**
+ * Note: because we use a book-end transition to finish the recents transition, we must
+ * either always merge the incoming transition, or always cancel the recents transition
+ * if we don't handle the incoming transition to ensure that the end transition is queued
+ * before any unhandled transitions.
+ */
@SuppressLint("NewApi")
- void merge(TransitionInfo info, SurfaceControl.Transaction t,
+ void merge(TransitionInfo info, SurfaceControl.Transaction t, IBinder mergeTarget,
Transitions.TransitionFinishCallback finishCallback) {
if (mFinishCB == null) {
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
"[%d] RecentsController.merge: skip, no finish callback",
mInstanceId);
- // This was no-op'd (likely a repeated start) and we've already sent finish.
+ // This was no-op'd (likely a repeated start) and we've already completed finish.
+ return;
+ }
+
+ if (Flags.enableShellTopTaskTracking()
+ && info.getType() == TRANSIT_END_RECENTS_TRANSITION
+ && mergeTarget == mTransition) {
+ // This is a pending finish, so merge the end transition to trigger completing the
+ // cleanup of the recents transition
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
+ "[%d] RecentsController.merge: TRANSIT_END_RECENTS_TRANSITION",
+ mInstanceId);
+ finishCallback.onTransitionFinished(null /* wct */);
return;
}
+
if (info.getType() == TRANSIT_SLEEP) {
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
"[%d] RecentsController.merge: transit_sleep", mInstanceId);
@@ -1245,7 +1283,8 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
return;
}
- if (mFinishCB == null) {
+ if (mFinishCB == null
+ || (Flags.enableShellTopTaskTracking() && mPendingFinishTransition != null)) {
Slog.e(TAG, "Duplicate call to finish");
return;
}
@@ -1254,19 +1293,22 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
&& !mWillFinishToHome
&& mPausingTasks != null
&& mState == STATE_NORMAL;
- if (returningToApp && allAppsAreTranslucent(mPausingTasks)) {
- mHomeTransitionObserver.notifyHomeVisibilityChanged(true);
- } else if (!toHome) {
- // For some transitions, we may have notified home activity that it became visible.
- // We need to notify the observer that we are no longer going home.
- mHomeTransitionObserver.notifyHomeVisibilityChanged(false);
+ if (!Flags.enableShellTopTaskTracking()) {
+ // This is only necessary when the recents transition is finished using a finishWCT,
+ // otherwise a new transition will notify the relevant observers
+ if (returningToApp && allAppsAreTranslucent(mPausingTasks)) {
+ mHomeTransitionObserver.notifyHomeVisibilityChanged(true);
+ } else if (!toHome) {
+ // For some transitions, we may have notified home activity that it became
+ // visible. We need to notify the observer that we are no longer going home.
+ mHomeTransitionObserver.notifyHomeVisibilityChanged(false);
+ }
}
+
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
"[%d] RecentsController.finishInner: toHome=%b userLeave=%b "
- + "willFinishToHome=%b state=%d",
- mInstanceId, toHome, sendUserLeaveHint, mWillFinishToHome, mState);
- final Transitions.TransitionFinishCallback finishCB = mFinishCB;
- mFinishCB = null;
+ + "willFinishToHome=%b state=%d reason=%s",
+ mInstanceId, toHome, sendUserLeaveHint, mWillFinishToHome, mState, reason);
final SurfaceControl.Transaction t = mFinishTransaction;
final WindowContainerTransaction wct = new WindowContainerTransaction();
@@ -1328,6 +1370,7 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
for (int i = 0; i < mClosingTasks.size(); ++i) {
cleanUpPausingOrClosingTask(mClosingTasks.get(i), wct, t, sendUserLeaveHint);
}
+
if (mPipTransaction != null && sendUserLeaveHint) {
SurfaceControl pipLeash = null;
TransitionInfo.Change pipChange = null;
@@ -1379,15 +1422,50 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
mTransitions.startTransition(TRANSIT_PIP, wct, null /* handler */);
// We need to clear the WCT to send finishWCT=null for Recents.
wct.clear();
+
+ if (Flags.enableShellTopTaskTracking()) {
+ // In this case, we've already started the PIP transition, so we can
+ // clean up immediately
+ mPendingRunnerFinishCb = runnerFinishCb;
+ onFinishInner(null);
+ return;
+ }
}
}
- mPipTaskId = -1;
- mPipTask = null;
- mPipTransaction = null;
}
}
+
+ if (Flags.enableShellTopTaskTracking()) {
+ if (!wct.isEmpty()) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
+ "[%d] RecentsController.finishInner: "
+ + "Queuing TRANSIT_END_RECENTS_TRANSITION", mInstanceId);
+ mPendingRunnerFinishCb = runnerFinishCb;
+ mPendingFinishTransition = mTransitions.startTransition(
+ TRANSIT_END_RECENTS_TRANSITION, wct,
+ new PendingFinishTransitionHandler());
+ } else {
+ // If there's no work to do, just go ahead and clean up
+ mPendingRunnerFinishCb = runnerFinishCb;
+ onFinishInner(null /* wct */);
+ }
+ } else {
+ mPendingRunnerFinishCb = runnerFinishCb;
+ onFinishInner(wct);
+ }
+ }
+
+ /**
+ * Runs the actual logic to finish the recents transition.
+ */
+ private void onFinishInner(@Nullable WindowContainerTransaction wct) {
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
+ "[%d] RecentsController.finishInner: Completing finish", mInstanceId);
+ final Transitions.TransitionFinishCallback finishCb = mFinishCB;
+ final IResultReceiver runnerFinishCb = mPendingRunnerFinishCb;
+
cleanUp();
- finishCB.onTransitionFinished(wct.isEmpty() ? null : wct);
+ finishCb.onTransitionFinished(wct);
if (runnerFinishCb != null) {
try {
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
@@ -1472,6 +1550,40 @@ public class RecentsTransitionHandler implements Transitions.TransitionHandler,
}
});
}
+
+ /**
+ * A temporary transition handler used with the pending finish transition, which runs the
+ * cleanup/finish logic once the pending transition is merged/handled.
+ * This is only initialized if Flags.enableShellTopTaskTracking() is enabled.
+ */
+ private class PendingFinishTransitionHandler implements Transitions.TransitionHandler {
+ @Override
+ public boolean startAnimation(@NonNull IBinder transition,
+ @NonNull TransitionInfo info,
+ @NonNull SurfaceControl.Transaction startTransaction,
+ @NonNull SurfaceControl.Transaction finishTransaction,
+ @NonNull Transitions.TransitionFinishCallback finishCallback) {
+ return false;
+ }
+
+ @Nullable
+ @Override
+ public WindowContainerTransaction handleRequest(@NonNull IBinder transition,
+ @NonNull TransitionRequestInfo request) {
+ return null;
+ }
+
+ @Override
+ public void onTransitionConsumed(@NonNull IBinder transition, boolean aborted,
+ @Nullable SurfaceControl.Transaction finishTransaction) {
+ // Once we have merged (or not if the WCT didn't result in any changes), then we can
+ // run the pending finish logic
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENTS_TRANSITION,
+ "[%d] RecentsController.onTransitionConsumed: "
+ + "Consumed pending finish transition", mInstanceId);
+ onFinishInner(null /* wct */);
+ }
+ };
};
/** Utility class to track the state of a task as-seen by recents. */
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 cc0e1df115c2..19a73f3631f2 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
@@ -55,7 +55,6 @@ import static com.android.wm.shell.splitscreen.SplitScreen.STAGE_TYPE_MAIN;
import static com.android.wm.shell.splitscreen.SplitScreen.STAGE_TYPE_SIDE;
import static com.android.wm.shell.splitscreen.SplitScreen.STAGE_TYPE_UNDEFINED;
import static com.android.wm.shell.splitscreen.SplitScreenController.ENTER_REASON_LAUNCHER;
-import static com.android.wm.shell.splitscreen.SplitScreenController.ENTER_REASON_MULTI_INSTANCE;
import static com.android.wm.shell.splitscreen.SplitScreenController.EXIT_REASON_APP_DOES_NOT_SUPPORT_MULTIWINDOW;
import static com.android.wm.shell.splitscreen.SplitScreenController.EXIT_REASON_APP_FINISHED;
import static com.android.wm.shell.splitscreen.SplitScreenController.EXIT_REASON_CHILD_TASK_ENTER_PIP;
@@ -1099,16 +1098,11 @@ public class StageCoordinator implements SplitLayout.SplitLayoutHandler,
void setSideStagePosition(@SplitPosition int sideStagePosition,
@Nullable WindowContainerTransaction wct) {
- setSideStagePosition(sideStagePosition, true /* updateBounds */, wct);
- }
-
- private void setSideStagePosition(@SplitPosition int sideStagePosition, boolean updateBounds,
- @Nullable WindowContainerTransaction wct) {
if (mSideStagePosition == sideStagePosition) return;
mSideStagePosition = sideStagePosition;
sendOnStagePositionChanged();
- if (mSideStage.mVisible && updateBounds) {
+ if (mSideStage.mVisible) {
if (wct == null) {
// onLayoutChanged builds/applies a wct with the contents of updateWindowBounds.
onLayoutSizeChanged(mSplitLayout);
@@ -1199,6 +1193,7 @@ public class StageCoordinator implements SplitLayout.SplitLayoutHandler,
if (!isSplitActive()) return;
final WindowContainerTransaction wct = new WindowContainerTransaction();
+ setSideStagePosition(SPLIT_POSITION_BOTTOM_OR_RIGHT, wct);
applyExitSplitScreen(childrenToTop, wct, exitReason);
}
@@ -1598,6 +1593,13 @@ public class StageCoordinator implements SplitLayout.SplitLayoutHandler,
}
if (present) {
updateRecentTasksSplitPair();
+ } else if (mMainStage.getChildCount() == 0 && mSideStage.getChildCount() == 0) {
+ mRecentTasks.ifPresent(recentTasks -> {
+ // remove the split pair mapping from recentTasks, and disable further updates
+ // to splits in the recents until we enter split again.
+ recentTasks.removeSplitPair(taskId);
+ });
+ exitSplitScreen(mMainStage, EXIT_REASON_ROOT_TASK_VANISHED);
}
for (int i = mListeners.size() - 1; i >= 0; --i) {
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 1d456aed5f4d..3f191497e1ed 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
@@ -203,6 +203,12 @@ public class Transitions implements RemoteCallable<Transitions>,
/** Transition type to minimize a task. */
public static final int TRANSIT_MINIMIZE = WindowManager.TRANSIT_FIRST_CUSTOM + 20;
+ /** Transition to start the recents transition */
+ public static final int TRANSIT_START_RECENTS_TRANSITION = TRANSIT_FIRST_CUSTOM + 21;
+
+ /** Transition to end the recents transition */
+ public static final int TRANSIT_END_RECENTS_TRANSITION = TRANSIT_FIRST_CUSTOM + 22;
+
/** Transition type for desktop mode transitions. */
public static final int TRANSIT_DESKTOP_MODE_TYPES =
WindowManager.TRANSIT_FIRST_CUSTOM + 100;
@@ -1875,6 +1881,8 @@ public class Transitions implements RemoteCallable<Transitions>,
case TRANSIT_SPLIT_PASSTHROUGH -> "SPLIT_PASSTHROUGH";
case TRANSIT_CLEANUP_PIP_EXIT -> "CLEANUP_PIP_EXIT";
case TRANSIT_MINIMIZE -> "MINIMIZE";
+ case TRANSIT_START_RECENTS_TRANSITION -> "START_RECENTS_TRANSITION";
+ case TRANSIT_END_RECENTS_TRANSITION -> "END_RECENTS_TRANSITION";
default -> "";
};
return typeStr + "(FIRST_CUSTOM+" + (transitType - TRANSIT_FIRST_CUSTOM) + ")";
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
index f2d8a782de34..5e3026a73971 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
@@ -465,7 +465,7 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
final RunningTaskInfo oldTaskInfo = decoration.mTaskInfo;
if (taskInfo.displayId != oldTaskInfo.displayId
- && !Flags.enableHandleInputFix()) {
+ && !DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
removeTaskFromEventReceiver(oldTaskInfo.displayId);
incrementEventReceiverTasks(taskInfo.displayId);
}
@@ -539,7 +539,7 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
decoration.close();
final int displayId = taskInfo.displayId;
if (mEventReceiversByDisplay.contains(displayId)
- && !Flags.enableHandleInputFix()) {
+ && !DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
removeTaskFromEventReceiver(displayId);
}
// Remove the decoration from the cache last because WindowDecoration#close could still
@@ -1234,7 +1234,7 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
relevantDecor.updateHoverAndPressStatus(ev);
final int action = ev.getActionMasked();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
- if (!mTransitionDragActive && !Flags.enableHandleInputFix()) {
+ if (!mTransitionDragActive && !DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
relevantDecor.closeHandleMenuIfNeeded(ev);
}
}
@@ -1277,7 +1277,7 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
}
final boolean shouldStartTransitionDrag =
relevantDecor.checkTouchEventInFocusedCaptionHandle(ev)
- || Flags.enableHandleInputFix();
+ || DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue();
if (dragFromStatusBarAllowed && shouldStartTransitionDrag) {
mTransitionDragActive = true;
}
@@ -1593,7 +1593,7 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
windowDecoration.relayout(taskInfo, startT, finishT,
false /* applyStartTransactionOnDraw */, false /* shouldSetTaskPositionAndCrop */,
mFocusTransitionObserver.hasGlobalFocus(taskInfo));
- if (!Flags.enableHandleInputFix()) {
+ if (!DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
incrementEventReceiverTasks(taskInfo.displayId);
}
}
@@ -1754,7 +1754,7 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
&& Flags.enableDesktopWindowingImmersiveHandleHiding()) {
decor.onInsetsStateChanged(insetsState);
}
- if (!Flags.enableHandleInputFix()) {
+ if (!DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
// If status bar inset is visible, top task is not in immersive mode.
// This value is only needed when the App Handle input is being handled
// through the global input monitor (hence the flag check) to ignore gestures
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecoration.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecoration.java
index d97632a9428c..d065ac33a958 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecoration.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecoration.java
@@ -628,13 +628,6 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
@Nullable
private Intent getBrowserLink() {
- // Do not show browser link in browser applications
- final ComponentName baseActivity = mTaskInfo.baseActivity;
- if (baseActivity != null && AppToWebUtils.isBrowserApp(mContext,
- baseActivity.getPackageName(), mUserContext.getUserId())) {
- return null;
- }
-
final Uri browserLink;
// If the captured link is available and has not expired, return the captured link.
// Otherwise, return the generic link which is set to null if a generic link is unavailable.
@@ -651,6 +644,18 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
}
+ @Nullable
+ private Intent getAppLink() {
+ return mWebUri == null ? null
+ : AppToWebUtils.getAppIntent(mWebUri, mContext.getPackageManager());
+ }
+
+ private boolean isBrowserApp() {
+ final ComponentName baseActivity = mTaskInfo.baseActivity;
+ return baseActivity != null && AppToWebUtils.isBrowserApp(mContext,
+ baseActivity.getPackageName(), mUserContext.getUserId());
+ }
+
UserHandle getUser() {
return mUserContext.getUser();
}
@@ -807,7 +812,7 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
*/
void disposeStatusBarInputLayer() {
if (!isAppHandle(mWindowDecorViewHolder)
- || !Flags.enableHandleInputFix()) {
+ || !DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
return;
}
asAppHandle(mWindowDecorViewHolder).disposeStatusBarInputLayer();
@@ -951,7 +956,7 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
}
controlsElement.mAlignment = RelayoutParams.OccludingCaptionElement.Alignment.END;
relayoutParams.mOccludingCaptionElements.add(controlsElement);
- } else if (isAppHandle && !Flags.enableHandleInputFix()) {
+ } else if (isAppHandle && !DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
// The focused decor (fullscreen/split) does not need to handle input because input in
// the App Handle is handled by the InputMonitor in DesktopModeWindowDecorViewModel.
// Note: This does not apply with the above flag enabled as the status bar input layer
@@ -1368,6 +1373,7 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
.shouldShowChangeAspectRatioButton(mTaskInfo);
final boolean inDesktopImmersive = mDesktopRepository
.isTaskInFullImmersiveState(mTaskInfo.taskId);
+ final boolean isBrowserApp = isBrowserApp();
mHandleMenu = mHandleMenuFactory.create(
this,
mWindowManagerWrapper,
@@ -1379,7 +1385,8 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
supportsMultiInstance,
shouldShowManageWindowsButton,
shouldShowChangeAspectRatioButton,
- getBrowserLink(),
+ isBrowserApp,
+ isBrowserApp ? getAppLink() : getBrowserLink(),
mResult.mCaptionWidth,
mResult.mCaptionHeight,
mResult.mCaptionX,
@@ -1560,13 +1567,13 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
*/
boolean checkTouchEventInFocusedCaptionHandle(MotionEvent ev) {
if (isHandleMenuActive() || !isAppHandle(mWindowDecorViewHolder)
- || Flags.enableHandleInputFix()) {
+ || DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
return false;
}
// The status bar input layer can only receive input in handle coordinates to begin with,
// so checking coordinates is unnecessary as input is always within handle bounds.
if (isAppHandle(mWindowDecorViewHolder)
- && Flags.enableHandleInputFix()
+ && DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()
&& isCaptionVisible()) {
return true;
}
@@ -1603,7 +1610,7 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
* @param ev the MotionEvent to compare
*/
void checkTouchEvent(MotionEvent ev) {
- if (mResult.mRootView == null || Flags.enableHandleInputFix()) return;
+ if (mResult.mRootView == null || DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) return;
final View caption = mResult.mRootView.findViewById(R.id.desktop_mode_caption);
final View handle = caption.findViewById(R.id.caption_handle);
final boolean inHandle = !isHandleMenuActive()
@@ -1616,7 +1623,7 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
// If the whole handle menu can be touched directly, rely on FLAG_WATCH_OUTSIDE_TOUCH.
// This is for the case that some of the handle menu is underneath the status bar.
if (isAppHandle(mWindowDecorViewHolder)
- && !Flags.enableHandleInputFix()) {
+ && !DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
mHandleMenu.checkMotionEvent(ev);
closeHandleMenuIfNeeded(ev);
}
@@ -1630,7 +1637,7 @@ public class DesktopModeWindowDecoration extends WindowDecoration<WindowDecorLin
* @param ev the MotionEvent to compare against.
*/
void updateHoverAndPressStatus(MotionEvent ev) {
- if (mResult.mRootView == null || Flags.enableHandleInputFix()) return;
+ if (mResult.mRootView == null || DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) return;
final View handle = mResult.mRootView.findViewById(R.id.caption_handle);
final boolean inHandle = !isHandleMenuActive()
&& checkTouchEventInFocusedCaptionHandle(ev);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt
index 2edc380756ac..54c247bff984 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt
@@ -39,12 +39,14 @@ import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
+import android.window.DesktopModeFlags
import android.window.SurfaceSyncGroup
+import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import androidx.compose.ui.graphics.toArgb
import androidx.core.view.isGone
-import com.android.window.flags.Flags
import com.android.wm.shell.R
+import com.android.wm.shell.apptoweb.isBrowserApp
import com.android.wm.shell.shared.split.SplitScreenConstants
import com.android.wm.shell.splitscreen.SplitScreenController
import com.android.wm.shell.windowdecor.additionalviewcontainer.AdditionalSystemViewContainer
@@ -73,7 +75,8 @@ class HandleMenu(
private val shouldShowNewWindowButton: Boolean,
private val shouldShowManageWindowsButton: Boolean,
private val shouldShowChangeAspectRatioButton: Boolean,
- private val openInBrowserIntent: Intent?,
+ private val isBrowserApp: Boolean,
+ private val openInAppOrBrowserIntent: Intent?,
private val captionWidth: Int,
private val captionHeight: Int,
captionX: Int,
@@ -83,7 +86,7 @@ class HandleMenu(
private val taskInfo: RunningTaskInfo = parentDecor.mTaskInfo
private val isViewAboveStatusBar: Boolean
- get() = (Flags.enableHandleInputFix() && !taskInfo.isFreeform)
+ get() = (DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue() && !taskInfo.isFreeform)
private val pillElevation: Int = loadDimensionPixelSize(
R.dimen.desktop_mode_handle_menu_pill_elevation)
@@ -111,7 +114,7 @@ class HandleMenu(
private val globalMenuPosition: Point = Point()
private val shouldShowBrowserPill: Boolean
- get() = openInBrowserIntent != null
+ get() = openInAppOrBrowserIntent != null
private val shouldShowMoreActionsPill: Boolean
get() = SHOULD_SHOW_SCREENSHOT_BUTTON || shouldShowNewWindowButton ||
@@ -128,7 +131,7 @@ class HandleMenu(
onNewWindowClickListener: () -> Unit,
onManageWindowsClickListener: () -> Unit,
onChangeAspectRatioClickListener: () -> Unit,
- openInBrowserClickListener: (Intent) -> Unit,
+ openInAppOrBrowserClickListener: (Intent) -> Unit,
onOpenByDefaultClickListener: () -> Unit,
onCloseMenuClickListener: () -> Unit,
onOutsideTouchListener: () -> Unit,
@@ -146,7 +149,7 @@ class HandleMenu(
onNewWindowClickListener = onNewWindowClickListener,
onManageWindowsClickListener = onManageWindowsClickListener,
onChangeAspectRatioClickListener = onChangeAspectRatioClickListener,
- openInBrowserClickListener = openInBrowserClickListener,
+ openInAppOrBrowserClickListener = openInAppOrBrowserClickListener,
onOpenByDefaultClickListener = onOpenByDefaultClickListener,
onCloseMenuClickListener = onCloseMenuClickListener,
onOutsideTouchListener = onOutsideTouchListener,
@@ -167,7 +170,7 @@ class HandleMenu(
onNewWindowClickListener: () -> Unit,
onManageWindowsClickListener: () -> Unit,
onChangeAspectRatioClickListener: () -> Unit,
- openInBrowserClickListener: (Intent) -> Unit,
+ openInAppOrBrowserClickListener: (Intent) -> Unit,
onOpenByDefaultClickListener: () -> Unit,
onCloseMenuClickListener: () -> Unit,
onOutsideTouchListener: () -> Unit,
@@ -181,7 +184,8 @@ class HandleMenu(
shouldShowBrowserPill = shouldShowBrowserPill,
shouldShowNewWindowButton = shouldShowNewWindowButton,
shouldShowManageWindowsButton = shouldShowManageWindowsButton,
- shouldShowChangeAspectRatioButton = shouldShowChangeAspectRatioButton
+ shouldShowChangeAspectRatioButton = shouldShowChangeAspectRatioButton,
+ isBrowserApp = isBrowserApp
).apply {
bind(taskInfo, appIconBitmap, appName, shouldShowMoreActionsPill)
this.onToDesktopClickListener = onToDesktopClickListener
@@ -190,8 +194,8 @@ class HandleMenu(
this.onNewWindowClickListener = onNewWindowClickListener
this.onManageWindowsClickListener = onManageWindowsClickListener
this.onChangeAspectRatioClickListener = onChangeAspectRatioClickListener
- this.onOpenInBrowserClickListener = {
- openInBrowserClickListener.invoke(openInBrowserIntent!!)
+ this.onOpenInAppOrBrowserClickListener = {
+ openInAppOrBrowserClickListener.invoke(openInAppOrBrowserIntent!!)
}
this.onOpenByDefaultClickListener = onOpenByDefaultClickListener
this.onCloseMenuClickListener = onCloseMenuClickListener
@@ -201,7 +205,8 @@ class HandleMenu(
val x = handleMenuPosition.x.toInt()
val y = handleMenuPosition.y.toInt()
handleMenuViewContainer =
- if ((!taskInfo.isFreeform && Flags.enableHandleInputFix()) || forceShowSystemBars) {
+ if ((!taskInfo.isFreeform && DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue())
+ || forceShowSystemBars) {
AdditionalSystemViewContainer(
windowManagerWrapper = windowManagerWrapper,
taskId = taskInfo.taskId,
@@ -237,7 +242,7 @@ class HandleMenu(
menuX = marginMenuStart
menuY = captionY + marginMenuTop
} else {
- if (Flags.enableHandleInputFix()) {
+ if (DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) {
// In a focused decor, we use global coordinates for handle menu. Therefore we
// need to account for other factors like split stage and menu/handle width to
// center the menu.
@@ -435,14 +440,15 @@ class HandleMenu(
/** The view within the Handle Menu, with options to change the windowing mode and more. */
@SuppressLint("ClickableViewAccessibility")
class HandleMenuView(
- context: Context,
+ private val context: Context,
menuWidth: Int,
captionHeight: Int,
private val shouldShowWindowingPill: Boolean,
private val shouldShowBrowserPill: Boolean,
private val shouldShowNewWindowButton: Boolean,
private val shouldShowManageWindowsButton: Boolean,
- private val shouldShowChangeAspectRatioButton: Boolean
+ private val shouldShowChangeAspectRatioButton: Boolean,
+ private val isBrowserApp: Boolean
) {
val rootView = LayoutInflater.from(context)
.inflate(R.layout.desktop_mode_window_decor_handle_menu, null /* root */) as View
@@ -472,11 +478,12 @@ class HandleMenu(
private val changeAspectRatioBtn = moreActionsPill
.requireViewById<Button>(R.id.change_aspect_ratio_button)
- // Open in Browser Pill.
- private val openInBrowserPill = rootView.requireViewById<View>(R.id.open_in_browser_pill)
- private val browserBtn = openInBrowserPill.requireViewById<Button>(
- R.id.open_in_browser_button)
- private val openByDefaultBtn = openInBrowserPill.requireViewById<ImageButton>(
+ // Open in Browser/App Pill.
+ private val openInAppOrBrowserPill = rootView.requireViewById<View>(
+ R.id.open_in_app_or_browser_pill)
+ private val openInAppOrBrowserBtn = openInAppOrBrowserPill.requireViewById<Button>(
+ R.id.open_in_app_or_browser_button)
+ private val openByDefaultBtn = openInAppOrBrowserPill.requireViewById<ImageButton>(
R.id.open_by_default_button)
private val decorThemeUtil = DecorThemeUtil(context)
private val animator = HandleMenuAnimator(rootView, menuWidth, captionHeight.toFloat())
@@ -490,7 +497,7 @@ class HandleMenu(
var onNewWindowClickListener: (() -> Unit)? = null
var onManageWindowsClickListener: (() -> Unit)? = null
var onChangeAspectRatioClickListener: (() -> Unit)? = null
- var onOpenInBrowserClickListener: (() -> Unit)? = null
+ var onOpenInAppOrBrowserClickListener: (() -> Unit)? = null
var onOpenByDefaultClickListener: (() -> Unit)? = null
var onCloseMenuClickListener: (() -> Unit)? = null
var onOutsideTouchListener: (() -> Unit)? = null
@@ -499,7 +506,7 @@ class HandleMenu(
fullscreenBtn.setOnClickListener { onToFullscreenClickListener?.invoke() }
splitscreenBtn.setOnClickListener { onToSplitScreenClickListener?.invoke() }
desktopBtn.setOnClickListener { onToDesktopClickListener?.invoke() }
- browserBtn.setOnClickListener { onOpenInBrowserClickListener?.invoke() }
+ openInAppOrBrowserBtn.setOnClickListener { onOpenInAppOrBrowserClickListener?.invoke() }
openByDefaultBtn.setOnClickListener {
onOpenByDefaultClickListener?.invoke()
}
@@ -535,10 +542,10 @@ class HandleMenu(
if (shouldShowMoreActionsPill) {
bindMoreActionsPill(style)
}
- bindOpenInBrowserPill(style)
+ bindOpenInAppOrBrowserPill(style)
}
- /** Animates the menu opening. */
+ /** Animates the menu openInAppOrBrowserg. */
fun animateOpenMenu() {
if (taskInfo.isFullscreen || taskInfo.isMultiWindow) {
animator.animateCaptionHandleExpandToOpen()
@@ -660,13 +667,20 @@ class HandleMenu(
}
}
- private fun bindOpenInBrowserPill(style: MenuStyle) {
- openInBrowserPill.apply {
+ private fun bindOpenInAppOrBrowserPill(style: MenuStyle) {
+ openInAppOrBrowserPill.apply {
isGone = !shouldShowBrowserPill
background.setTint(style.backgroundColor)
}
- browserBtn.apply {
+ val btnText = if (isBrowserApp) {
+ getString(R.string.open_in_app_text)
+ } else {
+ getString(R.string.open_in_browser_text)
+ }
+ openInAppOrBrowserBtn.apply {
+ text = btnText
+ contentDescription = btnText
setTextColor(style.textColor)
compoundDrawableTintList = ColorStateList.valueOf(style.textColor)
}
@@ -674,6 +688,8 @@ class HandleMenu(
openByDefaultBtn.imageTintList = ColorStateList.valueOf(style.textColor)
}
+ private fun getString(@StringRes resId: Int): String = context.resources.getString(resId)
+
private data class MenuStyle(
@ColorInt val backgroundColor: Int,
@ColorInt val textColor: Int,
@@ -708,7 +724,8 @@ interface HandleMenuFactory {
shouldShowNewWindowButton: Boolean,
shouldShowManageWindowsButton: Boolean,
shouldShowChangeAspectRatioButton: Boolean,
- openInBrowserIntent: Intent?,
+ isBrowserApp: Boolean,
+ openInAppOrBrowserIntent: Intent?,
captionWidth: Int,
captionHeight: Int,
captionX: Int,
@@ -729,7 +746,8 @@ object DefaultHandleMenuFactory : HandleMenuFactory {
shouldShowNewWindowButton: Boolean,
shouldShowManageWindowsButton: Boolean,
shouldShowChangeAspectRatioButton: Boolean,
- openInBrowserIntent: Intent?,
+ isBrowserApp: Boolean,
+ openInAppOrBrowserIntent: Intent?,
captionWidth: Int,
captionHeight: Int,
captionX: Int,
@@ -746,7 +764,8 @@ object DefaultHandleMenuFactory : HandleMenuFactory {
shouldShowNewWindowButton,
shouldShowManageWindowsButton,
shouldShowChangeAspectRatioButton,
- openInBrowserIntent,
+ isBrowserApp,
+ openInAppOrBrowserIntent,
captionWidth,
captionHeight,
captionX,
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuAnimator.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuAnimator.kt
index 0c475f12f53b..470e5a1d88b4 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuAnimator.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuAnimator.kt
@@ -74,7 +74,8 @@ class HandleMenuAnimator(
private val appInfoPill: ViewGroup = handleMenu.requireViewById(R.id.app_info_pill)
private val windowingPill: ViewGroup = handleMenu.requireViewById(R.id.windowing_pill)
private val moreActionsPill: ViewGroup = handleMenu.requireViewById(R.id.more_actions_pill)
- private val openInBrowserPill: ViewGroup = handleMenu.requireViewById(R.id.open_in_browser_pill)
+ private val openInAppOrBrowserPill: ViewGroup =
+ handleMenu.requireViewById(R.id.open_in_app_or_browser_pill)
/** Animates the opening of the handle menu. */
fun animateOpen() {
@@ -83,7 +84,7 @@ class HandleMenuAnimator(
animateAppInfoPillOpen()
animateWindowingPillOpen()
animateMoreActionsPillOpen()
- animateOpenInBrowserPill()
+ animateOpenInAppOrBrowserPill()
runAnimations {
appInfoPill.post {
appInfoPill.requireViewById<View>(R.id.collapse_menu_button).sendAccessibilityEvent(
@@ -103,7 +104,7 @@ class HandleMenuAnimator(
animateAppInfoPillOpen()
animateWindowingPillOpen()
animateMoreActionsPillOpen()
- animateOpenInBrowserPill()
+ animateOpenInAppOrBrowserPill()
runAnimations {
appInfoPill.post {
appInfoPill.requireViewById<View>(R.id.collapse_menu_button).sendAccessibilityEvent(
@@ -124,7 +125,7 @@ class HandleMenuAnimator(
animateAppInfoPillFadeOut()
windowingPillClose()
moreActionsPillClose()
- openInBrowserPillClose()
+ openInAppOrBrowserPillClose()
runAnimations(after)
}
@@ -141,7 +142,7 @@ class HandleMenuAnimator(
animateAppInfoPillFadeOut()
windowingPillClose()
moreActionsPillClose()
- openInBrowserPillClose()
+ openInAppOrBrowserPillClose()
runAnimations(after)
}
@@ -154,7 +155,7 @@ class HandleMenuAnimator(
appInfoPill.children.forEach { it.alpha = 0f }
windowingPill.alpha = 0f
moreActionsPill.alpha = 0f
- openInBrowserPill.alpha = 0f
+ openInAppOrBrowserPill.alpha = 0f
// Setup pivots.
handleMenu.pivotX = menuWidth / 2f
@@ -166,8 +167,8 @@ class HandleMenuAnimator(
moreActionsPill.pivotX = menuWidth / 2f
moreActionsPill.pivotY = appInfoPill.measuredHeight.toFloat()
- openInBrowserPill.pivotX = menuWidth / 2f
- openInBrowserPill.pivotY = appInfoPill.measuredHeight.toFloat()
+ openInAppOrBrowserPill.pivotX = menuWidth / 2f
+ openInAppOrBrowserPill.pivotY = appInfoPill.measuredHeight.toFloat()
}
private fun animateAppInfoPillOpen() {
@@ -297,36 +298,36 @@ class HandleMenuAnimator(
}
}
- private fun animateOpenInBrowserPill() {
+ private fun animateOpenInAppOrBrowserPill() {
// Open in Browser X & Y Scaling Animation
animators +=
- ObjectAnimator.ofFloat(openInBrowserPill, SCALE_X, HALF_INITIAL_SCALE, 1f).apply {
+ ObjectAnimator.ofFloat(openInAppOrBrowserPill, SCALE_X, HALF_INITIAL_SCALE, 1f).apply {
startDelay = BODY_SCALE_OPEN_DELAY
duration = BODY_SCALE_OPEN_DURATION
}
animators +=
- ObjectAnimator.ofFloat(openInBrowserPill, SCALE_Y, HALF_INITIAL_SCALE, 1f).apply {
+ ObjectAnimator.ofFloat(openInAppOrBrowserPill, SCALE_Y, HALF_INITIAL_SCALE, 1f).apply {
startDelay = BODY_SCALE_OPEN_DELAY
duration = BODY_SCALE_OPEN_DURATION
}
// Open in Browser Opacity Animation
animators +=
- ObjectAnimator.ofFloat(openInBrowserPill, ALPHA, 1f).apply {
+ ObjectAnimator.ofFloat(openInAppOrBrowserPill, ALPHA, 1f).apply {
startDelay = BODY_ALPHA_OPEN_DELAY
duration = BODY_ALPHA_OPEN_DURATION
}
// Open in Browser Elevation Animation
animators +=
- ObjectAnimator.ofFloat(openInBrowserPill, TRANSLATION_Z, 1f).apply {
+ ObjectAnimator.ofFloat(openInAppOrBrowserPill, TRANSLATION_Z, 1f).apply {
startDelay = ELEVATION_OPEN_DELAY
duration = BODY_ELEVATION_OPEN_DURATION
}
// Open in Browser Button Opacity Animation
- val button = openInBrowserPill.requireViewById<Button>(R.id.open_in_browser_button)
+ val button = openInAppOrBrowserPill.requireViewById<Button>(R.id.open_in_app_or_browser_button)
animators +=
ObjectAnimator.ofFloat(button, ALPHA, 1f).apply {
startDelay = BODY_ALPHA_OPEN_DELAY
@@ -438,33 +439,33 @@ class HandleMenuAnimator(
}
}
- private fun openInBrowserPillClose() {
+ private fun openInAppOrBrowserPillClose() {
// Open in Browser X & Y Scaling Animation
animators +=
- ObjectAnimator.ofFloat(openInBrowserPill, SCALE_X, HALF_INITIAL_SCALE).apply {
+ ObjectAnimator.ofFloat(openInAppOrBrowserPill, SCALE_X, HALF_INITIAL_SCALE).apply {
duration = BODY_CLOSE_DURATION
}
animators +=
- ObjectAnimator.ofFloat(openInBrowserPill, SCALE_Y, HALF_INITIAL_SCALE).apply {
+ ObjectAnimator.ofFloat(openInAppOrBrowserPill, SCALE_Y, HALF_INITIAL_SCALE).apply {
duration = BODY_CLOSE_DURATION
}
// Open in Browser Opacity Animation
animators +=
- ObjectAnimator.ofFloat(openInBrowserPill, ALPHA, 0f).apply {
+ ObjectAnimator.ofFloat(openInAppOrBrowserPill, ALPHA, 0f).apply {
duration = BODY_CLOSE_DURATION
}
animators +=
- ObjectAnimator.ofFloat(openInBrowserPill, ALPHA, 0f).apply {
+ ObjectAnimator.ofFloat(openInAppOrBrowserPill, ALPHA, 0f).apply {
duration = BODY_CLOSE_DURATION
}
// Upward Open in Browser y-translation Animation
val yStart: Float = -captionHeight / 2
animators +=
- ObjectAnimator.ofFloat(openInBrowserPill, TRANSLATION_Y, yStart).apply {
+ ObjectAnimator.ofFloat(openInAppOrBrowserPill, TRANSLATION_Y, yStart).apply {
duration = BODY_CLOSE_DURATION
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuImageButton.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuImageButton.kt
index cf82bb4f9919..8bc56e0807a8 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuImageButton.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenuImageButton.kt
@@ -16,13 +16,12 @@
package com.android.wm.shell.windowdecor
import android.app.ActivityManager.RunningTaskInfo
-import com.android.window.flags.Flags
-import com.android.wm.shell.windowdecor.additionalviewcontainer.AdditionalSystemViewContainer
-
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ImageButton
+import android.window.DesktopModeFlags
+import com.android.wm.shell.windowdecor.additionalviewcontainer.AdditionalSystemViewContainer
/**
* A custom [ImageButton] for buttons inside handle menu that intentionally doesn't handle hovers.
@@ -39,7 +38,7 @@ class HandleMenuImageButton(
lateinit var taskInfo: RunningTaskInfo
override fun onHoverEvent(motionEvent: MotionEvent): Boolean {
- if (Flags.enableHandleInputFix() || taskInfo.isFreeform) {
+ if (DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue() || taskInfo.isFreeform) {
return super.onHoverEvent(motionEvent)
} else {
return false
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/AppHandleViewHolder.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/AppHandleViewHolder.kt
index b5700ffb046b..503ad92d4d71 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/AppHandleViewHolder.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/viewholder/AppHandleViewHolder.kt
@@ -34,15 +34,14 @@ import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction
import android.widget.ImageButton
+import android.window.DesktopModeFlags
import androidx.core.view.ViewCompat
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat
import com.android.internal.policy.SystemBarUtils
-import com.android.window.flags.Flags
import com.android.wm.shell.R
import com.android.wm.shell.shared.animation.Interpolators
import com.android.wm.shell.windowdecor.WindowManagerWrapper
import com.android.wm.shell.windowdecor.additionalviewcontainer.AdditionalSystemViewContainer
-import com.android.wm.shell.windowdecor.viewholder.WindowDecorationViewHolder.Data
/**
* A desktop mode window decoration used when the window is in full "focus" (i.e. fullscreen/split).
@@ -141,7 +140,7 @@ internal class AppHandleViewHolder(
private fun createStatusBarInputLayer(handlePosition: Point,
handleWidth: Int,
handleHeight: Int) {
- if (!Flags.enableHandleInputFix()) return
+ if (!DesktopModeFlags.ENABLE_HANDLE_INPUT_FIX.isTrue()) return
statusBarInputLayer = AdditionalSystemViewContainer(context, windowManagerWrapper,
taskInfo.taskId, handlePosition.x, handlePosition.y, handleWidth, handleHeight,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/common/pip/PipAppOpsListenerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/common/pip/PipAppOpsListenerTest.java
new file mode 100644
index 000000000000..b9490b881d08
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/common/pip/PipAppOpsListenerTest.java
@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2024 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.common.pip;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+import android.app.AppOpsManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+import android.util.Pair;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.wm.shell.common.ShellExecutor;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+/**
+ * Unit test against {@link PipAppOpsListener}.
+ */
+@SmallTest
+@TestableLooper.RunWithLooper
+@RunWith(AndroidTestingRunner.class)
+public class PipAppOpsListenerTest {
+
+ @Mock private Context mMockContext;
+ @Mock private PackageManager mMockPackageManager;
+ @Mock private AppOpsManager mMockAppOpsManager;
+ @Mock private PipAppOpsListener.Callback mMockCallback;
+ @Mock private ShellExecutor mMockExecutor;
+
+ private PipAppOpsListener mPipAppOpsListener;
+
+ private ArgumentCaptor<AppOpsManager.OnOpChangedListener> mOnOpChangedListenerCaptor;
+ private ArgumentCaptor<Runnable> mRunnableArgumentCaptor;
+ private Pair<ComponentName, Integer> mTopPipActivity;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
+ when(mMockContext.getSystemService(Context.APP_OPS_SERVICE))
+ .thenReturn(mMockAppOpsManager);
+ mOnOpChangedListenerCaptor = ArgumentCaptor.forClass(
+ AppOpsManager.OnOpChangedListener.class);
+ mRunnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class);
+ }
+
+ @Test
+ public void onActivityPinned_registerAppOpsListener() {
+ String packageName = "com.android.test.pip";
+ mPipAppOpsListener = new PipAppOpsListener(mMockContext, mMockCallback, mMockExecutor);
+
+ mPipAppOpsListener.onActivityPinned(packageName);
+
+ verify(mMockAppOpsManager).startWatchingMode(
+ eq(AppOpsManager.OP_PICTURE_IN_PICTURE), eq(packageName),
+ any(AppOpsManager.OnOpChangedListener.class));
+ }
+
+ @Test
+ public void onActivityUnpinned_unregisterAppOpsListener() {
+ mPipAppOpsListener = new PipAppOpsListener(mMockContext, mMockCallback, mMockExecutor);
+
+ mPipAppOpsListener.onActivityUnpinned();
+
+ verify(mMockAppOpsManager).stopWatchingMode(any(AppOpsManager.OnOpChangedListener.class));
+ }
+
+ @Test
+ public void disablePipAppOps_dismissPip() throws PackageManager.NameNotFoundException {
+ String packageName = "com.android.test.pip";
+ mPipAppOpsListener = new PipAppOpsListener(mMockContext, mMockCallback, mMockExecutor);
+ // Set up the top pip activity info as mTopPipActivity
+ mTopPipActivity = new Pair<>(new ComponentName(packageName, "PipActivity"), 0);
+ mPipAppOpsListener.setTopPipActivityInfoSupplier(this::getTopPipActivity);
+ // Set up the application info as mApplicationInfo
+ ApplicationInfo applicationInfo = new ApplicationInfo();
+ applicationInfo.packageName = packageName;
+ when(mMockPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
+ .thenReturn(applicationInfo);
+ // Mock the mode to be **not** allowed
+ when(mMockAppOpsManager.checkOpNoThrow(anyInt(), anyInt(), eq(packageName)))
+ .thenReturn(AppOpsManager.MODE_DEFAULT);
+ // Set up the initial state
+ mPipAppOpsListener.onActivityPinned(packageName);
+ verify(mMockAppOpsManager).startWatchingMode(
+ eq(AppOpsManager.OP_PICTURE_IN_PICTURE), eq(packageName),
+ mOnOpChangedListenerCaptor.capture());
+ AppOpsManager.OnOpChangedListener opChangedListener = mOnOpChangedListenerCaptor.getValue();
+
+ opChangedListener.onOpChanged(String.valueOf(AppOpsManager.OP_PICTURE_IN_PICTURE),
+ packageName);
+
+ verify(mMockExecutor).execute(mRunnableArgumentCaptor.capture());
+ Runnable runnable = mRunnableArgumentCaptor.getValue();
+ runnable.run();
+ verify(mMockCallback).dismissPip();
+ }
+
+ @Test
+ public void disablePipAppOps_differentPackage_doNothing()
+ throws PackageManager.NameNotFoundException {
+ String packageName = "com.android.test.pip";
+ mPipAppOpsListener = new PipAppOpsListener(mMockContext, mMockCallback, mMockExecutor);
+ // Set up the top pip activity info as mTopPipActivity
+ mTopPipActivity = new Pair<>(new ComponentName(packageName, "PipActivity"), 0);
+ mPipAppOpsListener.setTopPipActivityInfoSupplier(this::getTopPipActivity);
+ // Set up the application info as mApplicationInfo
+ ApplicationInfo applicationInfo = new ApplicationInfo();
+ applicationInfo.packageName = packageName + ".modified";
+ when(mMockPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
+ .thenReturn(applicationInfo);
+ // Mock the mode to be **not** allowed
+ when(mMockAppOpsManager.checkOpNoThrow(anyInt(), anyInt(), eq(packageName)))
+ .thenReturn(AppOpsManager.MODE_DEFAULT);
+ // Set up the initial state
+ mPipAppOpsListener.onActivityPinned(packageName);
+ verify(mMockAppOpsManager).startWatchingMode(
+ eq(AppOpsManager.OP_PICTURE_IN_PICTURE), eq(packageName),
+ mOnOpChangedListenerCaptor.capture());
+ AppOpsManager.OnOpChangedListener opChangedListener = mOnOpChangedListenerCaptor.getValue();
+
+ opChangedListener.onOpChanged(String.valueOf(AppOpsManager.OP_PICTURE_IN_PICTURE),
+ packageName);
+
+ verifyZeroInteractions(mMockExecutor);
+ }
+
+ @Test
+ public void disablePipAppOps_nameNotFound_unregisterAppOpsListener()
+ throws PackageManager.NameNotFoundException {
+ String packageName = "com.android.test.pip";
+ mPipAppOpsListener = new PipAppOpsListener(mMockContext, mMockCallback, mMockExecutor);
+ // Set up the top pip activity info as mTopPipActivity
+ mTopPipActivity = new Pair<>(new ComponentName(packageName, "PipActivity"), 0);
+ mPipAppOpsListener.setTopPipActivityInfoSupplier(this::getTopPipActivity);
+ // Set up the application info as mApplicationInfo
+ ApplicationInfo applicationInfo = new ApplicationInfo();
+ applicationInfo.packageName = packageName;
+ when(mMockPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
+ .thenThrow(PackageManager.NameNotFoundException.class);
+ // Mock the mode to be **not** allowed
+ when(mMockAppOpsManager.checkOpNoThrow(anyInt(), anyInt(), eq(packageName)))
+ .thenReturn(AppOpsManager.MODE_DEFAULT);
+ // Set up the initial state
+ mPipAppOpsListener.onActivityPinned(packageName);
+ verify(mMockAppOpsManager).startWatchingMode(
+ eq(AppOpsManager.OP_PICTURE_IN_PICTURE), eq(packageName),
+ mOnOpChangedListenerCaptor.capture());
+ AppOpsManager.OnOpChangedListener opChangedListener = mOnOpChangedListenerCaptor.getValue();
+
+ opChangedListener.onOpChanged(String.valueOf(AppOpsManager.OP_PICTURE_IN_PICTURE),
+ packageName);
+
+ verify(mMockAppOpsManager).stopWatchingMode(any(AppOpsManager.OnOpChangedListener.class));
+ }
+
+ private Pair<ComponentName, Integer> getTopPipActivity(Context context) {
+ return mTopPipActivity;
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopImmersiveControllerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopImmersiveControllerTest.kt
index e05a0b54fcf4..a4f4d05d2079 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopImmersiveControllerTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopImmersiveControllerTest.kt
@@ -15,6 +15,7 @@
*/
package com.android.wm.shell.desktopmode
+import android.animation.AnimatorTestRule
import android.app.ActivityManager.RunningTaskInfo
import android.app.WindowConfiguration.WINDOW_CONFIG_BOUNDS
import android.graphics.Rect
@@ -24,6 +25,7 @@ import android.platform.test.annotations.DisableFlags
import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.SetFlagsRule
import android.testing.AndroidTestingRunner
+import android.testing.TestableLooper
import android.view.Display.DEFAULT_DISPLAY
import android.view.Surface
import android.view.SurfaceControl
@@ -43,6 +45,7 @@ import com.android.wm.shell.common.DisplayLayout
import com.android.wm.shell.desktopmode.DesktopTestHelpers.Companion.createFreeformTask
import com.android.wm.shell.sysui.ShellInit
import com.android.wm.shell.transition.Transitions
+import com.android.wm.shell.util.StubTransaction
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Rule
@@ -64,17 +67,19 @@ import org.mockito.kotlin.whenever
* Usage: atest WMShellUnitTests:DesktopImmersiveControllerTest
*/
@SmallTest
+@TestableLooper.RunWithLooper
@RunWith(AndroidTestingRunner::class)
class DesktopImmersiveControllerTest : ShellTestCase() {
@JvmField @Rule val setFlagsRule = SetFlagsRule()
+ @JvmField @Rule val animatorTestRule = AnimatorTestRule(this)
@Mock private lateinit var mockTransitions: Transitions
private lateinit var desktopRepository: DesktopRepository
@Mock private lateinit var mockDisplayController: DisplayController
@Mock private lateinit var mockShellTaskOrganizer: ShellTaskOrganizer
@Mock private lateinit var mockDisplayLayout: DisplayLayout
- private val transactionSupplier = { SurfaceControl.Transaction() }
+ private val transactionSupplier = { StubTransaction() }
private lateinit var controller: DesktopImmersiveController
@@ -89,10 +94,12 @@ class DesktopImmersiveControllerTest : ShellTestCase() {
(invocation.getArgument(0) as Rect).set(STABLE_BOUNDS)
}
controller = DesktopImmersiveController(
+ shellInit = mock(),
transitions = mockTransitions,
desktopRepository = desktopRepository,
displayController = mockDisplayController,
shellTaskOrganizer = mockShellTaskOrganizer,
+ shellCommandHandler = mock(),
transactionSupplier = transactionSupplier,
)
}
@@ -672,6 +679,60 @@ class DesktopImmersiveControllerTest : ShellTestCase() {
assertThat(controller.isImmersiveChange(transition, change)).isTrue()
}
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_FULLY_IMMERSIVE_IN_DESKTOP)
+ fun externalAnimateResizeChange_doesNotCleanUpPendingTransitionState() {
+ val task = createFreeformTask()
+ val mockBinder = mock(IBinder::class.java)
+ whenever(mockTransitions.startTransition(eq(TRANSIT_CHANGE), any(), eq(controller)))
+ .thenReturn(mockBinder)
+ desktopRepository.setTaskInFullImmersiveState(
+ displayId = task.displayId,
+ taskId = task.taskId,
+ immersive = true
+ )
+
+ controller.moveTaskToNonImmersive(task)
+
+ controller.animateResizeChange(
+ change = TransitionInfo.Change(task.token, SurfaceControl()).apply {
+ taskInfo = task
+ },
+ startTransaction = StubTransaction(),
+ finishTransaction = StubTransaction(),
+ finishCallback = { }
+ )
+ animatorTestRule.advanceTimeBy(DesktopImmersiveController.FULL_IMMERSIVE_ANIM_DURATION_MS)
+
+ assertThat(controller.state).isNotNull()
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_FULLY_IMMERSIVE_IN_DESKTOP)
+ fun startAnimation_missingChange_clearsState() {
+ val task = createFreeformTask()
+ val mockBinder = mock(IBinder::class.java)
+ whenever(mockTransitions.startTransition(eq(TRANSIT_CHANGE), any(), eq(controller)))
+ .thenReturn(mockBinder)
+ desktopRepository.setTaskInFullImmersiveState(
+ displayId = task.displayId,
+ taskId = task.taskId,
+ immersive = false
+ )
+
+ controller.moveTaskToImmersive(task)
+
+ controller.startAnimation(
+ transition = mockBinder,
+ info = createTransitionInfo(changes = emptyList()),
+ startTransaction = StubTransaction(),
+ finishTransaction = StubTransaction(),
+ finishCallback = {}
+ )
+
+ assertThat(controller.state).isNull()
+ }
+
private fun createTransitionInfo(
@TransitionType type: Int = TRANSIT_CHANGE,
@TransitionFlags flags: Int = 0,
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopRepositoryTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopRepositoryTest.kt
index 414c1a658b95..7f790d574a7e 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopRepositoryTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopRepositoryTest.kt
@@ -936,6 +936,28 @@ class DesktopRepositoryTest : ShellTestCase() {
}
@Test
+ fun saveBoundsBeforeMinimize_boundsSavedByTaskId() {
+ val taskId = 1
+ val bounds = Rect(0, 0, 200, 200)
+
+ repo.saveBoundsBeforeMinimize(taskId, bounds)
+
+ assertThat(repo.removeBoundsBeforeMinimize(taskId)).isEqualTo(bounds)
+ }
+
+ @Test
+ fun removeBoundsBeforeMinimize_returnsNullAfterBoundsRemoved() {
+ val taskId = 1
+ val bounds = Rect(0, 0, 200, 200)
+ repo.saveBoundsBeforeMinimize(taskId, bounds)
+ repo.removeBoundsBeforeMinimize(taskId)
+
+ val boundsBeforeMinimize = repo.removeBoundsBeforeMinimize(taskId)
+
+ assertThat(boundsBeforeMinimize).isNull()
+ }
+
+ @Test
fun getExpandedTasksOrdered_returnsFreeformTasksInCorrectOrder() {
repo.addTask(displayId = DEFAULT_DISPLAY, taskId = 3, isVisible = true)
repo.addTask(displayId = DEFAULT_DISPLAY, taskId = 2, isVisible = true)
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksLimiterTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksLimiterTest.kt
index 01b69aed8465..456b50da095b 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksLimiterTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksLimiterTest.kt
@@ -17,6 +17,7 @@
package com.android.wm.shell.desktopmode
import android.app.ActivityManager.RunningTaskInfo
+import android.graphics.Rect
import android.os.Binder
import android.os.Handler
import android.platform.test.annotations.DisableFlags
@@ -24,8 +25,10 @@ import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.SetFlagsRule
import android.testing.AndroidTestingRunner
import android.view.Display.DEFAULT_DISPLAY
+import android.view.SurfaceControl
import android.view.WindowManager.TRANSIT_OPEN
import android.view.WindowManager.TRANSIT_TO_BACK
+import android.window.TransitionInfo
import android.window.WindowContainerTransaction
import android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP_TYPE_REMOVE_TASK
import android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP_TYPE_REORDER
@@ -63,6 +66,7 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.any
+import org.mockito.Mockito.mock
import org.mockito.Mockito.spy
import org.mockito.Mockito.`when`
import org.mockito.kotlin.eq
@@ -235,6 +239,30 @@ class DesktopTasksLimiterTest : ShellTestCase() {
}
@Test
+ fun onTransitionReady_pendingTransition_changeTaskToBack_boundsSaved() {
+ val bounds = Rect(0, 0, 200, 200)
+ val transition = Binder()
+ val task = setUpFreeformTask()
+ desktopTasksLimiter.addPendingMinimizeChange(
+ transition, displayId = DEFAULT_DISPLAY, taskId = task.taskId)
+
+ val change = TransitionInfo.Change(task.token, mock(SurfaceControl::class.java)).apply {
+ mode = TRANSIT_TO_BACK
+ taskInfo = task
+ setStartAbsBounds(bounds)
+ }
+ desktopTasksLimiter.getTransitionObserver().onTransitionReady(
+ transition,
+ TransitionInfo(TRANSIT_OPEN, TransitionInfo.FLAG_NONE).apply { addChange(change) },
+ StubTransaction() /* startTransaction */,
+ StubTransaction() /* finishTransaction */)
+
+ assertThat(desktopTaskRepo.isMinimizedTask(taskId = task.taskId)).isTrue()
+ assertThat(desktopTaskRepo.removeBoundsBeforeMinimize(taskId = task.taskId)).isEqualTo(
+ bounds)
+ }
+
+ @Test
fun onTransitionReady_transitionMergedFromPending_taskIsMinimized() {
val mergedTransition = Binder()
val newTransition = Binder()
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
index bcb7461bfae7..5f58265b45f5 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/PipTaskOrganizerTest.java
@@ -47,6 +47,7 @@ import android.window.WindowContainerToken;
import androidx.test.filters.SmallTest;
import com.android.wm.shell.MockSurfaceControlHelper;
+import com.android.wm.shell.RootTaskDisplayAreaOrganizer;
import com.android.wm.shell.ShellTaskOrganizer;
import com.android.wm.shell.ShellTestCase;
import com.android.wm.shell.TestShellExecutor;
@@ -61,6 +62,7 @@ import com.android.wm.shell.common.pip.PipKeepClearAlgorithmInterface;
import com.android.wm.shell.common.pip.PipSnapAlgorithm;
import com.android.wm.shell.common.pip.PipUiEventLogger;
import com.android.wm.shell.common.pip.SizeSpecSource;
+import com.android.wm.shell.desktopmode.DesktopRepository;
import com.android.wm.shell.pip.phone.PhonePipMenuController;
import com.android.wm.shell.splitscreen.SplitScreenController;
@@ -90,6 +92,8 @@ public class PipTaskOrganizerTest extends ShellTestCase {
@Mock private PipSurfaceTransactionHelper mMockPipSurfaceTransactionHelper;
@Mock private PipUiEventLogger mMockPipUiEventLogger;
@Mock private Optional<SplitScreenController> mMockOptionalSplitScreen;
+ @Mock private Optional<DesktopRepository> mMockOptionalDesktopRepository;
+ @Mock private RootTaskDisplayAreaOrganizer mRootTaskDisplayAreaOrganizer;
@Mock private ShellTaskOrganizer mMockShellTaskOrganizer;
@Mock private PipParamsChangedForwarder mMockPipParamsChangedForwarder;
private TestShellExecutor mMainExecutor;
@@ -120,8 +124,10 @@ public class PipTaskOrganizerTest extends ShellTestCase {
mPipBoundsAlgorithm, mMockPhonePipMenuController, mMockPipAnimationController,
mMockPipSurfaceTransactionHelper, mMockPipTransitionController,
mMockPipParamsChangedForwarder, mMockOptionalSplitScreen,
- Optional.empty() /* pipPerfHintControllerOptional */, mMockDisplayController,
- mMockPipUiEventLogger, mMockShellTaskOrganizer, mMainExecutor);
+ Optional.empty() /* pipPerfHintControllerOptional */,
+ mMockOptionalDesktopRepository, mRootTaskDisplayAreaOrganizer,
+ mMockDisplayController, mMockPipUiEventLogger, mMockShellTaskOrganizer,
+ mMainExecutor);
mMainExecutor.flushAll();
preparePipTaskOrg();
preparePipSurfaceTransactionHelper();
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorationTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorationTests.java
index 41f57ae0fd97..884ad5c13f6a 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorationTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorationTests.java
@@ -262,8 +262,8 @@ public class DesktopModeWindowDecorationTests extends ShellTestCase {
doReturn(defaultDisplay).when(mMockDisplayController).getDisplay(Display.DEFAULT_DISPLAY);
doReturn(mInsetsState).when(mMockDisplayController).getInsetsState(anyInt());
when(mMockHandleMenuFactory.create(any(), any(), anyInt(), any(), any(), any(),
- anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean(), any(), anyInt(), anyInt(),
- anyInt(), anyInt()))
+ anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean(), any(),
+ anyInt(), anyInt(), anyInt(), anyInt()))
.thenReturn(mMockHandleMenu);
when(mMockMultiInstanceHelper.supportsMultiInstanceSplit(any())).thenReturn(false);
when(mMockAppHeaderViewHolderFactory.create(any(), any(), any(), any(), any(), any(), any(),
@@ -1440,9 +1440,30 @@ public class DesktopModeWindowDecorationTests extends ShellTestCase {
}
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_APP_TO_WEB)
+ public void browserApp_webUriUsedForBrowserApp() {
+ // Make {@link AppToWebUtils#isBrowserApp} return true
+ ResolveInfo resolveInfo = new ResolveInfo();
+ resolveInfo.handleAllWebDataURI = true;
+ resolveInfo.activityInfo = createActivityInfo();
+ when(mMockPackageManager.queryIntentActivitiesAsUser(any(), anyInt(), anyInt()))
+ .thenReturn(List.of(resolveInfo));
+
+ final ActivityManager.RunningTaskInfo taskInfo = createTaskInfo(true /* visible */);
+ final DesktopModeWindowDecoration decor = createWindowDecoration(
+ taskInfo, TEST_URI1 /* captured link */, TEST_URI2 /* web uri */,
+ TEST_URI3 /* generic link */);
+
+ // Verify web uri used for browser applications
+ createHandleMenu(decor);
+ verifyHandleMenuCreated(TEST_URI2);
+ }
+
+
private void verifyHandleMenuCreated(@Nullable Uri uri) {
verify(mMockHandleMenuFactory).create(any(), any(), anyInt(), any(), any(),
- any(), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean(),
+ any(), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean(),
argThat(intent -> (uri == null && intent == null) || intent.getData().equals(uri)),
anyInt(), anyInt(), anyInt(), anyInt());
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/HandleMenuTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/HandleMenuTest.kt
index ade17c61eda1..7ec2cbf9460e 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/HandleMenuTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/HandleMenuTest.kt
@@ -242,7 +242,7 @@ class HandleMenuTest : ShellTestCase() {
private fun createAndShowHandleMenu(
splitPosition: Int? = null,
- forceShowSystemBars: Boolean = false,
+ forceShowSystemBars: Boolean = false
): HandleMenu {
val layoutId = if (mockDesktopWindowDecoration.mTaskInfo.isFreeform) {
R.layout.desktop_mode_app_header
@@ -266,8 +266,9 @@ class HandleMenuTest : ShellTestCase() {
WindowManagerWrapper(mockWindowManager),
layoutId, appIcon, appName, splitScreenController, shouldShowWindowingPill = true,
shouldShowNewWindowButton = true, shouldShowManageWindowsButton = false,
- shouldShowChangeAspectRatioButton = false,
- null /* openInBrowserLink */, captionWidth = HANDLE_WIDTH, captionHeight = 50,
+ shouldShowChangeAspectRatioButton = false, isBrowserApp = false,
+ null /* openInAppOrBrowserIntent */, captionWidth = HANDLE_WIDTH,
+ captionHeight = 50,
captionX = captionX,
captionY = 0,
)
@@ -278,7 +279,7 @@ class HandleMenuTest : ShellTestCase() {
onNewWindowClickListener = mock(),
onManageWindowsClickListener = mock(),
onChangeAspectRatioClickListener = mock(),
- openInBrowserClickListener = mock(),
+ openInAppOrBrowserClickListener = mock(),
onOpenByDefaultClickListener = mock(),
onCloseMenuClickListener = mock(),
onOutsideTouchListener = mock(),
diff --git a/libs/appfunctions/api/current.txt b/libs/appfunctions/api/current.txt
index 0eda10112ee8..de402095e195 100644
--- a/libs/appfunctions/api/current.txt
+++ b/libs/appfunctions/api/current.txt
@@ -1,9 +1,29 @@
// Signature format: 2.0
package com.android.extensions.appfunctions {
+ public final class AppFunctionException extends java.lang.Exception {
+ ctor public AppFunctionException(int, @Nullable String);
+ ctor public AppFunctionException(int, @Nullable String, @NonNull android.os.Bundle);
+ method public int getErrorCategory();
+ method public int getErrorCode();
+ method @Nullable public String getErrorMessage();
+ method @NonNull public android.os.Bundle getExtras();
+ field public static final int ERROR_APP_UNKNOWN_ERROR = 3000; // 0xbb8
+ field public static final int ERROR_CANCELLED = 2001; // 0x7d1
+ field public static final int ERROR_CATEGORY_APP = 3; // 0x3
+ field public static final int ERROR_CATEGORY_REQUEST_ERROR = 1; // 0x1
+ field public static final int ERROR_CATEGORY_SYSTEM = 2; // 0x2
+ field public static final int ERROR_CATEGORY_UNKNOWN = 0; // 0x0
+ field public static final int ERROR_DENIED = 1000; // 0x3e8
+ field public static final int ERROR_DISABLED = 1002; // 0x3ea
+ field public static final int ERROR_FUNCTION_NOT_FOUND = 1003; // 0x3eb
+ field public static final int ERROR_INVALID_ARGUMENT = 1001; // 0x3e9
+ field public static final int ERROR_SYSTEM_ERROR = 2000; // 0x7d0
+ }
+
public final class AppFunctionManager {
ctor public AppFunctionManager(android.content.Context);
- method @RequiresPermission(anyOf={android.Manifest.permission.EXECUTE_APP_FUNCTIONS_TRUSTED, android.Manifest.permission.EXECUTE_APP_FUNCTIONS}, conditional=true) public void executeAppFunction(@NonNull com.android.extensions.appfunctions.ExecuteAppFunctionRequest, @NonNull java.util.concurrent.Executor, @NonNull android.os.CancellationSignal, @NonNull java.util.function.Consumer<com.android.extensions.appfunctions.ExecuteAppFunctionResponse>);
+ method @RequiresPermission(anyOf={android.Manifest.permission.EXECUTE_APP_FUNCTIONS_TRUSTED, android.Manifest.permission.EXECUTE_APP_FUNCTIONS}, conditional=true) public void executeAppFunction(@NonNull com.android.extensions.appfunctions.ExecuteAppFunctionRequest, @NonNull java.util.concurrent.Executor, @NonNull android.os.CancellationSignal, @NonNull android.os.OutcomeReceiver<com.android.extensions.appfunctions.ExecuteAppFunctionResponse,com.android.extensions.appfunctions.AppFunctionException>);
method @RequiresPermission(anyOf={android.Manifest.permission.EXECUTE_APP_FUNCTIONS_TRUSTED, android.Manifest.permission.EXECUTE_APP_FUNCTIONS}, conditional=true) public void isAppFunctionEnabled(@NonNull String, @NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Boolean,java.lang.Exception>);
method public void isAppFunctionEnabled(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Boolean,java.lang.Exception>);
method public void setAppFunctionEnabled(@NonNull String, int, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,java.lang.Exception>);
@@ -15,7 +35,7 @@ package com.android.extensions.appfunctions {
public abstract class AppFunctionService extends android.app.Service {
ctor public AppFunctionService();
method @NonNull public final android.os.IBinder onBind(@Nullable android.content.Intent);
- method @MainThread public abstract void onExecuteFunction(@NonNull com.android.extensions.appfunctions.ExecuteAppFunctionRequest, @NonNull String, @NonNull android.os.CancellationSignal, @NonNull java.util.function.Consumer<com.android.extensions.appfunctions.ExecuteAppFunctionResponse>);
+ method @MainThread public abstract void onExecuteFunction(@NonNull com.android.extensions.appfunctions.ExecuteAppFunctionRequest, @NonNull String, @NonNull android.os.CancellationSignal, @NonNull android.os.OutcomeReceiver<com.android.extensions.appfunctions.ExecuteAppFunctionResponse,com.android.extensions.appfunctions.AppFunctionException>);
field @NonNull public static final String BIND_APP_FUNCTION_SERVICE = "android.permission.BIND_APP_FUNCTION_SERVICE";
field @NonNull public static final String SERVICE_INTERFACE = "android.app.appfunctions.AppFunctionService";
}
@@ -35,27 +55,11 @@ package com.android.extensions.appfunctions {
}
public final class ExecuteAppFunctionResponse {
- method public int getErrorCategory();
- method @Nullable public String getErrorMessage();
+ ctor public ExecuteAppFunctionResponse(@NonNull android.app.appsearch.GenericDocument);
+ ctor public ExecuteAppFunctionResponse(@NonNull android.app.appsearch.GenericDocument, @NonNull android.os.Bundle);
method @NonNull public android.os.Bundle getExtras();
- method public int getResultCode();
method @NonNull public android.app.appsearch.GenericDocument getResultDocument();
- method public boolean isSuccess();
- method @NonNull public static com.android.extensions.appfunctions.ExecuteAppFunctionResponse newFailure(int, @Nullable String, @Nullable android.os.Bundle);
- method @NonNull public static com.android.extensions.appfunctions.ExecuteAppFunctionResponse newSuccess(@NonNull android.app.appsearch.GenericDocument, @Nullable android.os.Bundle);
- field public static final int ERROR_CATEGORY_APP = 3; // 0x3
- field public static final int ERROR_CATEGORY_REQUEST_ERROR = 1; // 0x1
- field public static final int ERROR_CATEGORY_SYSTEM = 2; // 0x2
- field public static final int ERROR_CATEGORY_UNKNOWN = 0; // 0x0
- field public static final String PROPERTY_RETURN_VALUE = "android_app_appfunctions_returnvalue";
- field public static final int RESULT_APP_UNKNOWN_ERROR = 3000; // 0xbb8
- field public static final int RESULT_CANCELLED = 2001; // 0x7d1
- field public static final int RESULT_DENIED = 1000; // 0x3e8
- field public static final int RESULT_DISABLED = 1002; // 0x3ea
- field public static final int RESULT_FUNCTION_NOT_FOUND = 1003; // 0x3eb
- field public static final int RESULT_INVALID_ARGUMENT = 1001; // 0x3e9
- field public static final int RESULT_OK = 0; // 0x0
- field public static final int RESULT_SYSTEM_ERROR = 2000; // 0x7d0
+ field public static final String PROPERTY_RETURN_VALUE = "androidAppfunctionsReturnValue";
}
}
diff --git a/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionException.java b/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionException.java
new file mode 100644
index 000000000000..28c3b3df9b1c
--- /dev/null
+++ b/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionException.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2024 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.extensions.appfunctions;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.os.Bundle;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/** Represents an app function related errors. */
+public final class AppFunctionException extends Exception {
+ /**
+ * The caller does not have the permission to execute an app function.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
+ */
+ public static final int ERROR_DENIED = 1000;
+
+ /**
+ * The caller supplied invalid arguments to the execution request.
+ *
+ * <p>This error may be considered similar to {@link IllegalArgumentException}.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
+ */
+ public static final int ERROR_INVALID_ARGUMENT = 1001;
+
+ /**
+ * The caller tried to execute a disabled app function.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
+ */
+ public static final int ERROR_DISABLED = 1002;
+
+ /**
+ * The caller tried to execute a function that does not exist.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
+ */
+ public static final int ERROR_FUNCTION_NOT_FOUND = 1003;
+
+ /**
+ * An internal unexpected error coming from the system.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_SYSTEM} category.
+ */
+ public static final int ERROR_SYSTEM_ERROR = 2000;
+
+ /**
+ * The operation was cancelled. Use this error code to report that a cancellation is done after
+ * receiving a cancellation signal.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_SYSTEM} category.
+ */
+ public static final int ERROR_CANCELLED = 2001;
+
+ /**
+ * An unknown error occurred while processing the call in the AppFunctionService.
+ *
+ * <p>This error is thrown when the service is connected in the remote application but an
+ * unexpected error is thrown from the bound application.
+ *
+ * <p>This error is in the {@link #ERROR_CATEGORY_APP} category.
+ */
+ public static final int ERROR_APP_UNKNOWN_ERROR = 3000;
+
+ /**
+ * The error category is unknown.
+ *
+ * <p>This is the default value for {@link #getErrorCategory}.
+ */
+ public static final int ERROR_CATEGORY_UNKNOWN = 0;
+
+ /**
+ * The error is caused by the app requesting a function execution.
+ *
+ * <p>For example, the caller provided invalid parameters in the execution request e.g. an
+ * invalid function ID.
+ *
+ * <p>Errors in the category fall in the range 1000-1999 inclusive.
+ */
+ public static final int ERROR_CATEGORY_REQUEST_ERROR = 1;
+
+ /**
+ * The error is caused by an issue in the system.
+ *
+ * <p>For example, the AppFunctionService implementation is not found by the system.
+ *
+ * <p>Errors in the category fall in the range 2000-2999 inclusive.
+ */
+ public static final int ERROR_CATEGORY_SYSTEM = 2;
+
+ /**
+ * The error is caused by the app providing the function.
+ *
+ * <p>For example, the app crashed when the system is executing the request.
+ *
+ * <p>Errors in the category fall in the range 3000-3999 inclusive.
+ */
+ public static final int ERROR_CATEGORY_APP = 3;
+
+ private final int mErrorCode;
+ @Nullable private final String mErrorMessage;
+ @NonNull private final Bundle mExtras;
+
+ public AppFunctionException(int errorCode, @Nullable String errorMessage) {
+ this(errorCode, errorMessage, Bundle.EMPTY);
+ }
+
+ public AppFunctionException(
+ int errorCode, @Nullable String errorMessage, @NonNull Bundle extras) {
+ mErrorCode = errorCode;
+ mErrorMessage = errorMessage;
+ mExtras = extras;
+ }
+
+ /** Returns one of the {@code ERROR} constants. */
+ @ErrorCode
+ public int getErrorCode() {
+ return mErrorCode;
+ }
+
+ /** Returns the error message. */
+ @Nullable
+ public String getErrorMessage() {
+ return mErrorMessage;
+ }
+
+ /**
+ * Returns the error category.
+ *
+ * <p>This method categorizes errors based on their underlying cause, allowing developers to
+ * implement targeted error handling and provide more informative error messages to users. It
+ * maps ranges of error codes to specific error categories.
+ *
+ * <p>This method returns {@code ERROR_CATEGORY_UNKNOWN} if the error code does not belong to
+ * any error category.
+ *
+ * <p>See {@link ErrorCategory} for a complete list of error categories and their corresponding
+ * error code ranges.
+ */
+ @ErrorCategory
+ public int getErrorCategory() {
+ if (mErrorCode >= 1000 && mErrorCode < 2000) {
+ return ERROR_CATEGORY_REQUEST_ERROR;
+ }
+ if (mErrorCode >= 2000 && mErrorCode < 3000) {
+ return ERROR_CATEGORY_SYSTEM;
+ }
+ if (mErrorCode >= 3000 && mErrorCode < 4000) {
+ return ERROR_CATEGORY_APP;
+ }
+ return ERROR_CATEGORY_UNKNOWN;
+ }
+
+ @NonNull
+ public Bundle getExtras() {
+ return mExtras;
+ }
+
+ /**
+ * Error codes.
+ *
+ * @hide
+ */
+ @IntDef(
+ prefix = {"ERROR_"},
+ value = {
+ ERROR_DENIED,
+ ERROR_APP_UNKNOWN_ERROR,
+ ERROR_FUNCTION_NOT_FOUND,
+ ERROR_SYSTEM_ERROR,
+ ERROR_INVALID_ARGUMENT,
+ ERROR_DISABLED,
+ ERROR_CANCELLED
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface ErrorCode {}
+
+ /**
+ * Error categories.
+ *
+ * @hide
+ */
+ @IntDef(
+ prefix = {"ERROR_CATEGORY_"},
+ value = {
+ ERROR_CATEGORY_UNKNOWN,
+ ERROR_CATEGORY_REQUEST_ERROR,
+ ERROR_CATEGORY_APP,
+ ERROR_CATEGORY_SYSTEM
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface ErrorCategory {}
+}
diff --git a/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionManager.java b/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionManager.java
index d64593d8ff5f..9eb66a33fedc 100644
--- a/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionManager.java
+++ b/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionManager.java
@@ -31,7 +31,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Objects;
import java.util.concurrent.Executor;
-import java.util.function.Consumer;
/**
* Provides app functions related functionalities.
@@ -115,7 +114,9 @@ public final class AppFunctionManager {
@NonNull ExecuteAppFunctionRequest sidecarRequest,
@NonNull @CallbackExecutor Executor executor,
@NonNull CancellationSignal cancellationSignal,
- @NonNull Consumer<ExecuteAppFunctionResponse> callback) {
+ @NonNull
+ OutcomeReceiver<ExecuteAppFunctionResponse, AppFunctionException>
+ callback) {
Objects.requireNonNull(sidecarRequest);
Objects.requireNonNull(executor);
Objects.requireNonNull(callback);
@@ -126,10 +127,20 @@ public final class AppFunctionManager {
platformRequest,
executor,
cancellationSignal,
- (platformResponse) -> {
- callback.accept(
- SidecarConverter.getSidecarExecuteAppFunctionResponse(
- platformResponse));
+ new OutcomeReceiver<>() {
+ @Override
+ public void onResult(
+ android.app.appfunctions.ExecuteAppFunctionResponse result) {
+ callback.onResult(
+ SidecarConverter.getSidecarExecuteAppFunctionResponse(result));
+ }
+
+ @Override
+ public void onError(
+ android.app.appfunctions.AppFunctionException exception) {
+ callback.onError(
+ SidecarConverter.getSidecarAppFunctionException(exception));
+ }
});
}
diff --git a/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionService.java b/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionService.java
index 1a4d9da8bd63..55f579138218 100644
--- a/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionService.java
+++ b/libs/appfunctions/java/com/android/extensions/appfunctions/AppFunctionService.java
@@ -16,7 +16,8 @@
package com.android.extensions.appfunctions;
-import static android.Manifest.permission.BIND_APP_FUNCTION_SERVICE;
+import static com.android.extensions.appfunctions.SidecarConverter.getPlatformAppFunctionException;
+import static com.android.extensions.appfunctions.SidecarConverter.getPlatformExecuteAppFunctionResponse;
import android.annotation.MainThread;
import android.annotation.NonNull;
@@ -26,8 +27,7 @@ import android.content.Intent;
import android.os.Binder;
import android.os.CancellationSignal;
import android.os.IBinder;
-
-import java.util.function.Consumer;
+import android.os.OutcomeReceiver;
/**
* Abstract base class to provide app functions to the system.
@@ -79,10 +79,18 @@ public abstract class AppFunctionService extends Service {
platformRequest),
callingPackage,
cancellationSignal,
- (sidecarResponse) -> {
- callback.accept(
- SidecarConverter.getPlatformExecuteAppFunctionResponse(
- sidecarResponse));
+ new OutcomeReceiver<>() {
+ @Override
+ public void onResult(ExecuteAppFunctionResponse result) {
+ callback.onResult(
+ getPlatformExecuteAppFunctionResponse(result));
+ }
+
+ @Override
+ public void onError(AppFunctionException exception) {
+ callback.onError(
+ getPlatformAppFunctionException(exception));
+ }
});
});
@@ -115,12 +123,14 @@ public abstract class AppFunctionService extends Service {
* @param request The function execution request.
* @param callingPackage The package name of the app that is requesting the execution.
* @param cancellationSignal A signal to cancel the execution.
- * @param callback A callback to report back the result.
+ * @param callback A callback to report back the result or error.
*/
@MainThread
public abstract void onExecuteFunction(
@NonNull ExecuteAppFunctionRequest request,
@NonNull String callingPackage,
@NonNull CancellationSignal cancellationSignal,
- @NonNull Consumer<ExecuteAppFunctionResponse> callback);
+ @NonNull
+ OutcomeReceiver<ExecuteAppFunctionResponse, AppFunctionException>
+ callback);
}
diff --git a/libs/appfunctions/java/com/android/extensions/appfunctions/ExecuteAppFunctionResponse.java b/libs/appfunctions/java/com/android/extensions/appfunctions/ExecuteAppFunctionResponse.java
index 7c5ddcd9edfb..0826f04a50dd 100644
--- a/libs/appfunctions/java/com/android/extensions/appfunctions/ExecuteAppFunctionResponse.java
+++ b/libs/appfunctions/java/com/android/extensions/appfunctions/ExecuteAppFunctionResponse.java
@@ -16,23 +16,14 @@
package com.android.extensions.appfunctions;
-import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.Nullable;
+import android.app.appfunctions.AppFunctionManager;
import android.app.appsearch.GenericDocument;
import android.os.Bundle;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
import java.util.Objects;
-/**
- * The response to an app function execution.
- *
- * <p>This class copies {@link android.app.appfunctions.ExecuteAppFunctionResponse} without parcel
- * functionality and exposes it here as a sidecar library (avoiding direct dependency on the
- * platform API).
- */
+/** The response to an app function execution. */
public final class ExecuteAppFunctionResponse {
/**
* The name of the property that stores the function return value within the {@code
@@ -48,113 +39,7 @@ public final class ExecuteAppFunctionResponse {
*
* <p>See {@link #getResultDocument} for more information on extracting the return value.
*/
- public static final String PROPERTY_RETURN_VALUE = "android_app_appfunctions_returnvalue";
-
- /**
- * The call was successful.
- *
- * <p>This result code does not belong in an error category.
- */
- public static final int RESULT_OK = 0;
-
- /**
- * The caller does not have the permission to execute an app function.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
- */
- public static final int RESULT_DENIED = 1000;
-
- /**
- * The caller supplied invalid arguments to the execution request.
- *
- * <p>This error may be considered similar to {@link IllegalArgumentException}.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
- */
- public static final int RESULT_INVALID_ARGUMENT = 1001;
-
- /**
- * The caller tried to execute a disabled app function.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
- */
- public static final int RESULT_DISABLED = 1002;
-
- /**
- * The caller tried to execute a function that does not exist.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_REQUEST_ERROR} category.
- */
- public static final int RESULT_FUNCTION_NOT_FOUND = 1003;
-
- /**
- * An internal unexpected error coming from the system.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_SYSTEM} category.
- */
- public static final int RESULT_SYSTEM_ERROR = 2000;
-
- /**
- * The operation was cancelled. Use this error code to report that a cancellation is done after
- * receiving a cancellation signal.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_SYSTEM} category.
- */
- public static final int RESULT_CANCELLED = 2001;
-
- /**
- * An unknown error occurred while processing the call in the AppFunctionService.
- *
- * <p>This error is thrown when the service is connected in the remote application but an
- * unexpected error is thrown from the bound application.
- *
- * <p>This error is in the {@link #ERROR_CATEGORY_APP} category.
- */
- public static final int RESULT_APP_UNKNOWN_ERROR = 3000;
-
- /**
- * The error category is unknown.
- *
- * <p>This is the default value for {@link #getErrorCategory}.
- */
- public static final int ERROR_CATEGORY_UNKNOWN = 0;
-
- /**
- * The error is caused by the app requesting a function execution.
- *
- * <p>For example, the caller provided invalid parameters in the execution request e.g. an
- * invalid function ID.
- *
- * <p>Errors in the category fall in the range 1000-1999 inclusive.
- */
- public static final int ERROR_CATEGORY_REQUEST_ERROR = 1;
-
- /**
- * The error is caused by an issue in the system.
- *
- * <p>For example, the AppFunctionService implementation is not found by the system.
- *
- * <p>Errors in the category fall in the range 2000-2999 inclusive.
- */
- public static final int ERROR_CATEGORY_SYSTEM = 2;
-
- /**
- * The error is caused by the app providing the function.
- *
- * <p>For example, the app crashed when the system is executing the request.
- *
- * <p>Errors in the category fall in the range 3000-3999 inclusive.
- */
- public static final int ERROR_CATEGORY_APP = 3;
-
- /** The result code of the app function execution. */
- @ResultCode private final int mResultCode;
-
- /**
- * The error message associated with the result, if any. This is {@code null} if the result code
- * is {@link #RESULT_OK}.
- */
- @Nullable private final String mErrorMessage;
+ public static final String PROPERTY_RETURN_VALUE = "androidAppfunctionsReturnValue";
/**
* Returns the return value of the executed function.
@@ -169,99 +54,21 @@ public final class ExecuteAppFunctionResponse {
/** Returns the additional metadata data relevant to this function execution response. */
@NonNull private final Bundle mExtras;
- private ExecuteAppFunctionResponse(
- @NonNull GenericDocument resultDocument,
- @NonNull Bundle extras,
- @ResultCode int resultCode,
- @Nullable String errorMessage) {
- mResultDocument = Objects.requireNonNull(resultDocument);
- mExtras = Objects.requireNonNull(extras);
- mResultCode = resultCode;
- mErrorMessage = errorMessage;
- }
-
/**
- * Returns result codes from throwable.
- *
- * @hide
- */
- static @ResultCode int getResultCode(@NonNull Throwable t) {
- if (t instanceof IllegalArgumentException) {
- return ExecuteAppFunctionResponse.RESULT_INVALID_ARGUMENT;
- }
- return ExecuteAppFunctionResponse.RESULT_APP_UNKNOWN_ERROR;
- }
-
- /**
- * Returns a successful response.
- *
* @param resultDocument The return value of the executed function.
- * @param extras The additional metadata data relevant to this function execution response.
*/
- @NonNull
- public static ExecuteAppFunctionResponse newSuccess(
- @NonNull GenericDocument resultDocument, @Nullable Bundle extras) {
- Objects.requireNonNull(resultDocument);
- Bundle actualExtras = getActualExtras(extras);
-
- return new ExecuteAppFunctionResponse(
- resultDocument, actualExtras, RESULT_OK, /* errorMessage= */ null);
+ public ExecuteAppFunctionResponse(@NonNull GenericDocument resultDocument) {
+ this(resultDocument, Bundle.EMPTY);
}
/**
- * Returns a failure response.
- *
- * @param resultCode The result code of the app function execution.
- * @param extras The additional metadata data relevant to this function execution response.
- * @param errorMessage The error message associated with the result, if any.
- */
- @NonNull
- public static ExecuteAppFunctionResponse newFailure(
- @ResultCode int resultCode, @Nullable String errorMessage, @Nullable Bundle extras) {
- if (resultCode == RESULT_OK) {
- throw new IllegalArgumentException("resultCode must not be RESULT_OK");
- }
- Bundle actualExtras = getActualExtras(extras);
- GenericDocument emptyDocument = new GenericDocument.Builder<>("", "", "").build();
- return new ExecuteAppFunctionResponse(
- emptyDocument, actualExtras, resultCode, errorMessage);
- }
-
- private static Bundle getActualExtras(@Nullable Bundle extras) {
- if (extras == null) {
- return Bundle.EMPTY;
- }
- return extras;
- }
-
- /**
- * Returns the error category of the {@link ExecuteAppFunctionResponse}.
- *
- * <p>This method categorizes errors based on their underlying cause, allowing developers to
- * implement targeted error handling and provide more informative error messages to users. It
- * maps ranges of result codes to specific error categories.
- *
- * <p>When constructing a {@link #newFailure} response, use the appropriate result code value to
- * ensure correct categorization of the failed response.
- *
- * <p>This method returns {@code ERROR_CATEGORY_UNKNOWN} if the result code does not belong to
- * any error category, for example, in the case of a successful result with {@link #RESULT_OK}.
- *
- * <p>See {@link ErrorCategory} for a complete list of error categories and their corresponding
- * result code ranges.
+ * @param resultDocument The return value of the executed function.
+ * @param extras The additional metadata for this function execution response.
*/
- @ErrorCategory
- public int getErrorCategory() {
- if (mResultCode >= 1000 && mResultCode < 2000) {
- return ERROR_CATEGORY_REQUEST_ERROR;
- }
- if (mResultCode >= 2000 && mResultCode < 3000) {
- return ERROR_CATEGORY_SYSTEM;
- }
- if (mResultCode >= 3000 && mResultCode < 4000) {
- return ERROR_CATEGORY_APP;
- }
- return ERROR_CATEGORY_UNKNOWN;
+ public ExecuteAppFunctionResponse(
+ @NonNull GenericDocument resultDocument, @NonNull Bundle extras) {
+ mResultDocument = Objects.requireNonNull(resultDocument);
+ mExtras = Objects.requireNonNull(extras);
}
/**
@@ -269,9 +76,6 @@ public final class ExecuteAppFunctionResponse {
*
* <p>The {@link #PROPERTY_RETURN_VALUE} key can be used to obtain the return value.
*
- * <p>An empty document is returned if {@link #isSuccess} is {@code false} or if the executed
- * function does not produce a return value.
- *
* <p>Sample code for extracting the return value:
*
* <pre>
@@ -283,77 +87,17 @@ public final class ExecuteAppFunctionResponse {
* // Do something with the returnValue
* }
* </pre>
+ *
+ * @see AppFunctionManager on how to determine the expected function return.
*/
@NonNull
public GenericDocument getResultDocument() {
return mResultDocument;
}
- /** Returns the extras of the app function execution. */
+ /** Returns the additional metadata for this function execution response. */
@NonNull
public Bundle getExtras() {
return mExtras;
}
-
- /**
- * Returns {@code true} if {@link #getResultCode} equals {@link
- * ExecuteAppFunctionResponse#RESULT_OK}.
- */
- public boolean isSuccess() {
- return getResultCode() == RESULT_OK;
- }
-
- /**
- * Returns one of the {@code RESULT} constants defined in {@link ExecuteAppFunctionResponse}.
- */
- @ResultCode
- public int getResultCode() {
- return mResultCode;
- }
-
- /**
- * Returns the error message associated with this result.
- *
- * <p>If {@link #isSuccess} is {@code true}, the error message is always {@code null}.
- */
- @Nullable
- public String getErrorMessage() {
- return mErrorMessage;
- }
-
- /**
- * Result codes.
- *
- * @hide
- */
- @IntDef(
- prefix = {"RESULT_"},
- value = {
- RESULT_OK,
- RESULT_DENIED,
- RESULT_APP_UNKNOWN_ERROR,
- RESULT_SYSTEM_ERROR,
- RESULT_FUNCTION_NOT_FOUND,
- RESULT_INVALID_ARGUMENT,
- RESULT_DISABLED,
- RESULT_CANCELLED
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface ResultCode {}
-
- /**
- * Error categories.
- *
- * @hide
- */
- @IntDef(
- prefix = {"ERROR_CATEGORY_"},
- value = {
- ERROR_CATEGORY_UNKNOWN,
- ERROR_CATEGORY_REQUEST_ERROR,
- ERROR_CATEGORY_APP,
- ERROR_CATEGORY_SYSTEM
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface ErrorCategory {}
}
diff --git a/libs/appfunctions/java/com/android/extensions/appfunctions/SidecarConverter.java b/libs/appfunctions/java/com/android/extensions/appfunctions/SidecarConverter.java
index 56f2725fccc7..5e1fc7e684e2 100644
--- a/libs/appfunctions/java/com/android/extensions/appfunctions/SidecarConverter.java
+++ b/libs/appfunctions/java/com/android/extensions/appfunctions/SidecarConverter.java
@@ -52,13 +52,21 @@ public final class SidecarConverter {
@NonNull
public static android.app.appfunctions.ExecuteAppFunctionResponse
getPlatformExecuteAppFunctionResponse(@NonNull ExecuteAppFunctionResponse response) {
- if (response.isSuccess()) {
- return android.app.appfunctions.ExecuteAppFunctionResponse.newSuccess(
- response.getResultDocument(), response.getExtras());
- } else {
- return android.app.appfunctions.ExecuteAppFunctionResponse.newFailure(
- response.getResultCode(), response.getErrorMessage(), response.getExtras());
- }
+ return new android.app.appfunctions.ExecuteAppFunctionResponse(
+ response.getResultDocument(), response.getExtras());
+ }
+
+ /**
+ * Converts sidecar's {@link AppFunctionException} into platform's {@link
+ * android.app.appfunctions.AppFunctionException}
+ *
+ * @hide
+ */
+ @NonNull
+ public static android.app.appfunctions.AppFunctionException
+ getPlatformAppFunctionException(@NonNull AppFunctionException exception) {
+ return new android.app.appfunctions.AppFunctionException(
+ exception.getErrorCode(), exception.getErrorMessage(), exception.getExtras());
}
/**
@@ -86,12 +94,19 @@ public final class SidecarConverter {
@NonNull
public static ExecuteAppFunctionResponse getSidecarExecuteAppFunctionResponse(
@NonNull android.app.appfunctions.ExecuteAppFunctionResponse response) {
- if (response.isSuccess()) {
- return ExecuteAppFunctionResponse.newSuccess(
- response.getResultDocument(), response.getExtras());
- } else {
- return ExecuteAppFunctionResponse.newFailure(
- response.getResultCode(), response.getErrorMessage(), response.getExtras());
- }
+ return new ExecuteAppFunctionResponse(response.getResultDocument(), response.getExtras());
+ }
+
+ /**
+ * Converts platform's {@link android.app.appfunctions.AppFunctionException} into
+ * sidecar's {@link AppFunctionException}
+ *
+ * @hide
+ */
+ @NonNull
+ public static AppFunctionException getSidecarAppFunctionException(
+ @NonNull android.app.appfunctions.AppFunctionException exception) {
+ return new AppFunctionException(
+ exception.getErrorCode(), exception.getErrorMessage(), exception.getExtras());
}
}
diff --git a/libs/appfunctions/tests/src/com/android/extensions/appfunctions/tests/SidecarConverterTest.kt b/libs/appfunctions/tests/src/com/android/extensions/appfunctions/tests/SidecarConverterTest.kt
index 6118e6ce4ab2..11202d58e484 100644
--- a/libs/appfunctions/tests/src/com/android/extensions/appfunctions/tests/SidecarConverterTest.kt
+++ b/libs/appfunctions/tests/src/com/android/extensions/appfunctions/tests/SidecarConverterTest.kt
@@ -16,6 +16,7 @@
package com.android.extensions.appfunctions.tests
+import android.app.appfunctions.AppFunctionException
import android.app.appfunctions.ExecuteAppFunctionRequest
import android.app.appfunctions.ExecuteAppFunctionResponse
import android.app.appsearch.GenericDocument
@@ -83,44 +84,38 @@ class SidecarConverterTest {
GenericDocument.Builder<GenericDocument.Builder<*>>("", "", "")
.setPropertyBoolean(ExecuteAppFunctionResponse.PROPERTY_RETURN_VALUE, true)
.build()
- val platformResponse = ExecuteAppFunctionResponse.newSuccess(resultGd, null)
+ val platformResponse = ExecuteAppFunctionResponse(resultGd)
val sidecarResponse = SidecarConverter.getSidecarExecuteAppFunctionResponse(
platformResponse
)
- assertThat(sidecarResponse.isSuccess).isTrue()
assertThat(
sidecarResponse.resultDocument.getProperty(
ExecuteAppFunctionResponse.PROPERTY_RETURN_VALUE
)
)
.isEqualTo(booleanArrayOf(true))
- assertThat(sidecarResponse.resultCode).isEqualTo(ExecuteAppFunctionResponse.RESULT_OK)
- assertThat(sidecarResponse.errorMessage).isNull()
}
@Test
- fun getSidecarExecuteAppFunctionResponse_errorResponse_sameContents() {
- val emptyGd = GenericDocument.Builder<GenericDocument.Builder<*>>("", "", "").build()
- val platformResponse =
- ExecuteAppFunctionResponse.newFailure(
- ExecuteAppFunctionResponse.RESULT_SYSTEM_ERROR,
- null,
- null
+ fun getSidecarAppFunctionException_sameContents() {
+ val bundle = Bundle()
+ bundle.putString("key", "value")
+ val platformException =
+ AppFunctionException(
+ AppFunctionException.ERROR_SYSTEM_ERROR,
+ "error",
+ bundle
)
- val sidecarResponse = SidecarConverter.getSidecarExecuteAppFunctionResponse(
- platformResponse
+ val sidecarException = SidecarConverter.getSidecarAppFunctionException(
+ platformException
)
- assertThat(sidecarResponse.isSuccess).isFalse()
- assertThat(sidecarResponse.resultDocument.namespace).isEqualTo(emptyGd.namespace)
- assertThat(sidecarResponse.resultDocument.id).isEqualTo(emptyGd.id)
- assertThat(sidecarResponse.resultDocument.schemaType).isEqualTo(emptyGd.schemaType)
- assertThat(sidecarResponse.resultCode)
- .isEqualTo(ExecuteAppFunctionResponse.RESULT_SYSTEM_ERROR)
- assertThat(sidecarResponse.errorMessage).isNull()
+ assertThat(sidecarException.errorCode).isEqualTo(AppFunctionException.ERROR_SYSTEM_ERROR)
+ assertThat(sidecarException.errorMessage).isEqualTo("error")
+ assertThat(sidecarException.extras.getString("key")).isEqualTo("value")
}
@Test
@@ -130,46 +125,38 @@ class SidecarConverterTest {
.setPropertyBoolean(ExecuteAppFunctionResponse.PROPERTY_RETURN_VALUE, true)
.build()
val sidecarResponse =
- com.android.extensions.appfunctions.ExecuteAppFunctionResponse.newSuccess(
- resultGd,
- null
- )
+ com.android.extensions.appfunctions.ExecuteAppFunctionResponse(resultGd)
val platformResponse = SidecarConverter.getPlatformExecuteAppFunctionResponse(
sidecarResponse
)
- assertThat(platformResponse.isSuccess).isTrue()
assertThat(
platformResponse.resultDocument.getProperty(
ExecuteAppFunctionResponse.PROPERTY_RETURN_VALUE
)
)
.isEqualTo(booleanArrayOf(true))
- assertThat(platformResponse.resultCode).isEqualTo(ExecuteAppFunctionResponse.RESULT_OK)
- assertThat(platformResponse.errorMessage).isNull()
}
@Test
- fun getPlatformExecuteAppFunctionResponse_errorResponse_sameContents() {
- val emptyGd = GenericDocument.Builder<GenericDocument.Builder<*>>("", "", "").build()
- val sidecarResponse =
- com.android.extensions.appfunctions.ExecuteAppFunctionResponse.newFailure(
- ExecuteAppFunctionResponse.RESULT_SYSTEM_ERROR,
- null,
- null
+ fun getPlatformAppFunctionException_sameContents() {
+ val bundle = Bundle()
+ bundle.putString("key", "value")
+ val sidecarException =
+ com.android.extensions.appfunctions.AppFunctionException(
+ AppFunctionException.ERROR_SYSTEM_ERROR,
+ "error",
+ bundle
)
- val platformResponse = SidecarConverter.getPlatformExecuteAppFunctionResponse(
- sidecarResponse
+ val platformException = SidecarConverter.getPlatformAppFunctionException(
+ sidecarException
)
- assertThat(platformResponse.isSuccess).isFalse()
- assertThat(platformResponse.resultDocument.namespace).isEqualTo(emptyGd.namespace)
- assertThat(platformResponse.resultDocument.id).isEqualTo(emptyGd.id)
- assertThat(platformResponse.resultDocument.schemaType).isEqualTo(emptyGd.schemaType)
- assertThat(platformResponse.resultCode)
- .isEqualTo(ExecuteAppFunctionResponse.RESULT_SYSTEM_ERROR)
- assertThat(platformResponse.errorMessage).isNull()
+ assertThat(platformException.errorCode)
+ .isEqualTo(AppFunctionException.ERROR_SYSTEM_ERROR)
+ assertThat(platformException.errorMessage).isEqualTo("error")
+ assertThat(platformException.extras.getString("key")).isEqualTo("value")
}
}
diff --git a/media/java/android/media/MediaCas.java b/media/java/android/media/MediaCas.java
index 88efed55c11f..3f9126aa9456 100644
--- a/media/java/android/media/MediaCas.java
+++ b/media/java/android/media/MediaCas.java
@@ -1000,7 +1000,10 @@ public final class MediaCas implements AutoCloseable {
@SystemApi
@RequiresPermission(android.Manifest.permission.TUNER_RESOURCE_ACCESS)
public boolean updateResourcePriority(int priority, int niceValue) {
- return mTunerResourceManager.updateClientPriority(mClientId, priority, niceValue);
+ if (mTunerResourceManager != null) {
+ return mTunerResourceManager.updateClientPriority(mClientId, priority, niceValue);
+ }
+ return false;
}
/**
@@ -1017,7 +1020,9 @@ public final class MediaCas implements AutoCloseable {
@SystemApi
@RequiresPermission(android.Manifest.permission.TUNER_RESOURCE_ACCESS)
public void setResourceHolderRetain(boolean resourceHolderRetain) {
- mTunerResourceManager.setResourceHolderRetain(mClientId, resourceHolderRetain);
+ if (mTunerResourceManager != null) {
+ mTunerResourceManager.setResourceHolderRetain(mClientId, resourceHolderRetain);
+ }
}
IHwBinder getBinder() {
diff --git a/media/java/android/media/flags/media_better_together.aconfig b/media/java/android/media/flags/media_better_together.aconfig
index 52a21e241ba8..ba2398c12607 100644
--- a/media/java/android/media/flags/media_better_together.aconfig
+++ b/media/java/android/media/flags/media_better_together.aconfig
@@ -51,7 +51,7 @@ flag {
is_exported: true
namespace: "media_tv"
description: "Enables the following type constant in MediaRoute2Info: LINE_ANALOG, LINE_DIGITAL, AUX_LINE"
- bug: "301713440"
+ bug: "375691732"
}
flag {
diff --git a/media/java/android/media/quality/AmbientBacklightSettings.java b/media/java/android/media/quality/AmbientBacklightSettings.java
index 391eb225bcab..bb782bf1aee4 100644
--- a/media/java/android/media/quality/AmbientBacklightSettings.java
+++ b/media/java/android/media/quality/AmbientBacklightSettings.java
@@ -26,6 +26,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
+ * Settings for ambient backlight.
* @hide
*/
public class AmbientBacklightSettings implements Parcelable {
diff --git a/media/java/android/media/quality/IMediaQualityManager.aidl b/media/java/android/media/quality/IMediaQualityManager.aidl
index e6c79dd9681f..250d59b7c2d7 100644
--- a/media/java/android/media/quality/IMediaQualityManager.aidl
+++ b/media/java/android/media/quality/IMediaQualityManager.aidl
@@ -30,20 +30,22 @@ import android.media.quality.SoundProfile;
*/
interface IMediaQualityManager {
PictureProfile createPictureProfile(in PictureProfile pp);
- void updatePictureProfile(in long id, in PictureProfile pp);
- void removePictureProfile(in long id);
- PictureProfile getPictureProfileById(in long id);
+ void updatePictureProfile(in String id, in PictureProfile pp);
+ void removePictureProfile(in String id);
+ PictureProfile getPictureProfile(in int type, in String name);
List<PictureProfile> getPictureProfilesByPackage(in String packageName);
List<PictureProfile> getAvailablePictureProfiles();
- List<PictureProfile> getAllPictureProfiles();
+ List<String> getPictureProfilePackageNames();
+ List<String> getPictureProfileAllowList();
+ void setPictureProfileAllowList(in List<String> packages);
SoundProfile createSoundProfile(in SoundProfile pp);
- void updateSoundProfile(in long id, in SoundProfile pp);
- void removeSoundProfile(in long id);
- SoundProfile getSoundProfileById(in long id);
+ void updateSoundProfile(in String id, in SoundProfile pp);
+ void removeSoundProfile(in String id);
+ SoundProfile getSoundProfileById(in String id);
List<SoundProfile> getSoundProfilesByPackage(in String packageName);
List<SoundProfile> getAvailableSoundProfiles();
- List<SoundProfile> getAllSoundProfiles();
+ List<String> getSoundProfilePackageNames();
void registerPictureProfileCallback(in IPictureProfileCallback cb);
void registerSoundProfileCallback(in ISoundProfileCallback cb);
diff --git a/media/java/android/media/quality/IPictureProfileCallback.aidl b/media/java/android/media/quality/IPictureProfileCallback.aidl
index 05441cde31e7..34aa2b061caf 100644
--- a/media/java/android/media/quality/IPictureProfileCallback.aidl
+++ b/media/java/android/media/quality/IPictureProfileCallback.aidl
@@ -17,6 +17,7 @@
package android.media.quality;
+import android.media.quality.ParamCapability;
import android.media.quality.PictureProfile;
/**
@@ -24,7 +25,9 @@ import android.media.quality.PictureProfile;
* @hide
*/
oneway interface IPictureProfileCallback {
- void onPictureProfileAdded(in long id, in PictureProfile p);
- void onPictureProfileUpdated(in long id, in PictureProfile p);
- void onPictureProfileRemoved(in long id, in PictureProfile p);
+ void onPictureProfileAdded(in String id, in PictureProfile p);
+ void onPictureProfileUpdated(in String id, in PictureProfile p);
+ void onPictureProfileRemoved(in String id, in PictureProfile p);
+ void onParamCapabilitiesChanged(in String id, in List<ParamCapability> caps);
+ void onError(in int err);
}
diff --git a/media/java/android/media/quality/MediaQualityManager.java b/media/java/android/media/quality/MediaQualityManager.java
index 38a2025535f4..26d83aca3e7b 100644
--- a/media/java/android/media/quality/MediaQualityManager.java
+++ b/media/java/android/media/quality/MediaQualityManager.java
@@ -19,6 +19,7 @@ package android.media.quality;
import android.annotation.CallbackExecutor;
import android.annotation.FlaggedApi;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.SystemService;
import android.content.Context;
import android.media.tv.flags.Flags;
@@ -63,7 +64,7 @@ public final class MediaQualityManager {
mService = service;
IPictureProfileCallback ppCallback = new IPictureProfileCallback.Stub() {
@Override
- public void onPictureProfileAdded(long profileId, PictureProfile profile) {
+ public void onPictureProfileAdded(String profileId, PictureProfile profile) {
synchronized (mLock) {
for (PictureProfileCallbackRecord record : mPpCallbackRecords) {
// TODO: filter callback record
@@ -72,7 +73,7 @@ public final class MediaQualityManager {
}
}
@Override
- public void onPictureProfileUpdated(long profileId, PictureProfile profile) {
+ public void onPictureProfileUpdated(String profileId, PictureProfile profile) {
synchronized (mLock) {
for (PictureProfileCallbackRecord record : mPpCallbackRecords) {
// TODO: filter callback record
@@ -81,7 +82,7 @@ public final class MediaQualityManager {
}
}
@Override
- public void onPictureProfileRemoved(long profileId, PictureProfile profile) {
+ public void onPictureProfileRemoved(String profileId, PictureProfile profile) {
synchronized (mLock) {
for (PictureProfileCallbackRecord record : mPpCallbackRecords) {
// TODO: filter callback record
@@ -89,6 +90,24 @@ public final class MediaQualityManager {
}
}
}
+ @Override
+ public void onParamCapabilitiesChanged(String profileId, List<ParamCapability> caps) {
+ synchronized (mLock) {
+ for (PictureProfileCallbackRecord record : mPpCallbackRecords) {
+ // TODO: filter callback record
+ record.postParamCapabilitiesChanged(profileId, caps);
+ }
+ }
+ }
+ @Override
+ public void onError(int err) {
+ synchronized (mLock) {
+ for (PictureProfileCallbackRecord record : mPpCallbackRecords) {
+ // TODO: filter callback record
+ record.postError(err);
+ }
+ }
+ }
};
ISoundProfileCallback spCallback = new ISoundProfileCallback.Stub() {
@Override
@@ -175,14 +194,17 @@ public final class MediaQualityManager {
/**
- * Gets picture profile by given profile ID.
- * @return the corresponding picture profile if available; {@code null} if the ID doesn't
- * exist or the profile is not accessible to the caller.
+ * Gets picture profile by given profile type and name.
+ *
+ * @return the corresponding picture profile if available; {@code null} if the name doesn't
+ * exist.
* @hide
*/
- public PictureProfile getPictureProfileById(long profileId) {
+ @Nullable
+ public PictureProfile getPictureProfile(
+ @PictureProfile.ProfileType int type, @NonNull String name) {
try {
- return mService.getPictureProfileById(profileId);
+ return mService.getPictureProfile(type, name);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -190,11 +212,13 @@ public final class MediaQualityManager {
/**
- * @SystemApi gets profiles that available to the given package
- * @hide
+ * Gets profiles that available to the given package.
+ *
+ * @hide @SystemApi
*/
+ @NonNull
@RequiresPermission(android.Manifest.permission.MANAGE_GLOBAL_PICTURE_QUALITY_SERVICE)
- public List<PictureProfile> getPictureProfilesByPackage(String packageName) {
+ public List<PictureProfile> getPictureProfilesByPackage(@NonNull String packageName) {
try {
return mService.getPictureProfilesByPackage(packageName);
} catch (RemoteException e) {
@@ -215,13 +239,16 @@ public final class MediaQualityManager {
}
/**
- * @SystemApi all stored picture profiles of all packages
- * @hide
+ * Gets all package names whose picture profiles are available.
+ *
+ * @see #getPictureProfilesByPackage(String)
+ * @hide @SystemApi
*/
+ @NonNull
@RequiresPermission(android.Manifest.permission.MANAGE_GLOBAL_PICTURE_QUALITY_SERVICE)
- public List<PictureProfile> getAllPictureProfiles() {
+ public List<String> getPictureProfilePackageNames() {
try {
- return mService.getAllPictureProfiles();
+ return mService.getPictureProfilePackageNames();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -231,10 +258,12 @@ public final class MediaQualityManager {
/**
* Creates a picture profile and store it in the system.
*
- * @return the stored profile with an assigned profile ID.
+ * @return the stored profile with an assigned profile ID. {@code null} if it's not created
+ * successfully.
* @hide
*/
- public PictureProfile createPictureProfile(PictureProfile pp) {
+ @Nullable
+ public PictureProfile createPictureProfile(@NonNull PictureProfile pp) {
try {
return mService.createPictureProfile(pp);
} catch (RemoteException e) {
@@ -247,7 +276,7 @@ public final class MediaQualityManager {
* Updates an existing picture profile and store it in the system.
* @hide
*/
- public void updatePictureProfile(long profileId, PictureProfile pp) {
+ public void updatePictureProfile(@NonNull String profileId, @NonNull PictureProfile pp) {
try {
mService.updatePictureProfile(profileId, pp);
} catch (RemoteException e) {
@@ -260,7 +289,7 @@ public final class MediaQualityManager {
* Removes a picture profile from the system.
* @hide
*/
- public void removePictureProfile(long profileId) {
+ public void removePictureProfile(@NonNull String profileId) {
try {
mService.removePictureProfile(profileId);
} catch (RemoteException e) {
@@ -307,7 +336,7 @@ public final class MediaQualityManager {
* exist or the profile is not accessible to the caller.
* @hide
*/
- public SoundProfile getSoundProfileById(long profileId) {
+ public SoundProfile getSoundProfileById(String profileId) {
try {
return mService.getSoundProfileById(profileId);
} catch (RemoteException e) {
@@ -346,9 +375,9 @@ public final class MediaQualityManager {
* @hide
*/
@RequiresPermission(android.Manifest.permission.MANAGE_GLOBAL_SOUND_QUALITY_SERVICE)
- public List<SoundProfile> getAllSoundProfiles() {
+ public List<String> getSoundProfilePackageNames() {
try {
- return mService.getAllSoundProfiles();
+ return mService.getSoundProfilePackageNames();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -374,7 +403,7 @@ public final class MediaQualityManager {
* Updates an existing sound profile and store it in the system.
* @hide
*/
- public void updateSoundProfile(long profileId, SoundProfile sp) {
+ public void updateSoundProfile(String profileId, SoundProfile sp) {
try {
mService.updateSoundProfile(profileId, sp);
} catch (RemoteException e) {
@@ -387,7 +416,7 @@ public final class MediaQualityManager {
* Removes a sound profile from the system.
* @hide
*/
- public void removeSoundProfile(long profileId) {
+ public void removeSoundProfile(String profileId) {
try {
mService.removeSoundProfile(profileId);
} catch (RemoteException e) {
@@ -399,7 +428,8 @@ public final class MediaQualityManager {
* Gets capability information of the given parameters.
* @hide
*/
- public List<ParamCapability> getParamCapabilities(List<String> names) {
+ @NonNull
+ public List<ParamCapability> getParamCapabilities(@NonNull List<String> names) {
try {
return mService.getParamCapabilities(names);
} catch (RemoteException e) {
@@ -408,7 +438,38 @@ public final class MediaQualityManager {
}
/**
+ * Gets the allowlist of packages that can create and removed picture profiles
+ *
+ * @see #createPictureProfile(PictureProfile)
+ * @see #removePictureProfile(String)
+ * @hide
+ */
+ @RequiresPermission(android.Manifest.permission.MANAGE_GLOBAL_PICTURE_QUALITY_SERVICE)
+ @NonNull
+ public List<String> getPictureProfileAllowList() {
+ try {
+ return mService.getPictureProfileAllowList();
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Sets the allowlist of packages that can create and removed picture profiles
+ * @hide
+ */
+ @RequiresPermission(android.Manifest.permission.MANAGE_GLOBAL_PICTURE_QUALITY_SERVICE)
+ public void setPictureProfileAllowList(@NonNull List<String> packageNames) {
+ try {
+ mService.setPictureProfileAllowList(packageNames);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Returns {@code true} if media quality HAL is implemented; {@code false} otherwise.
+ * @hide
*/
public boolean isSupported() {
try {
@@ -581,7 +642,7 @@ public final class MediaQualityManager {
return mCallback;
}
- public void postPictureProfileAdded(final long id, PictureProfile profile) {
+ public void postPictureProfileAdded(final String id, PictureProfile profile) {
mExecutor.execute(new Runnable() {
@Override
@@ -591,7 +652,7 @@ public final class MediaQualityManager {
});
}
- public void postPictureProfileUpdated(final long id, PictureProfile profile) {
+ public void postPictureProfileUpdated(final String id, PictureProfile profile) {
mExecutor.execute(new Runnable() {
@Override
public void run() {
@@ -600,7 +661,7 @@ public final class MediaQualityManager {
});
}
- public void postPictureProfileRemoved(final long id, PictureProfile profile) {
+ public void postPictureProfileRemoved(final String id, PictureProfile profile) {
mExecutor.execute(new Runnable() {
@Override
public void run() {
@@ -608,6 +669,24 @@ public final class MediaQualityManager {
}
});
}
+
+ public void postParamCapabilitiesChanged(final String id, List<ParamCapability> caps) {
+ mExecutor.execute(new Runnable() {
+ @Override
+ public void run() {
+ mCallback.onParamCapabilitiesChanged(id, caps);
+ }
+ });
+ }
+
+ public void postError(int error) {
+ mExecutor.execute(new Runnable() {
+ @Override
+ public void run() {
+ mCallback.onError(error);
+ }
+ });
+ }
}
private static final class SoundProfileCallbackRecord {
@@ -681,24 +760,57 @@ public final class MediaQualityManager {
*/
public abstract static class PictureProfileCallback {
/**
+ * This is invoked when a picture profile has been added.
+ *
+ * @param profileId the ID of the profile.
+ * @param profile the newly added profile.
* @hide
*/
- public void onPictureProfileAdded(long id, PictureProfile profile) {
+ public void onPictureProfileAdded(
+ @NonNull String profileId, @NonNull PictureProfile profile) {
}
+
/**
+ * This is invoked when a picture profile has been updated.
+ *
+ * @param profileId the ID of the profile.
+ * @param profile the profile with updated info.
* @hide
*/
- public void onPictureProfileUpdated(long id, PictureProfile profile) {
+ public void onPictureProfileUpdated(
+ @NonNull String profileId, @NonNull PictureProfile profile) {
}
+
/**
+ * This is invoked when a picture profile has been removed.
+ *
+ * @param profileId the ID of the profile.
+ * @param profile the removed profile.
* @hide
*/
- public void onPictureProfileRemoved(long id, PictureProfile profile) {
+ public void onPictureProfileRemoved(
+ @NonNull String profileId, @NonNull PictureProfile profile) {
}
+
/**
+ * This is invoked when an issue has occurred.
+ *
+ * @param errorCode the error code
* @hide
*/
- public void onError(int errorCode) {
+ public void onError(@PictureProfile.ErrorCode int errorCode) {
+ }
+
+ /**
+ * This is invoked when parameter capabilities has been changed due to status changes of the
+ * content.
+ *
+ * @param profileId the ID of the profile used by the media content.
+ * @param updatedCaps the updated capabilities.
+ * @hide
+ */
+ public void onParamCapabilitiesChanged(
+ @NonNull String profileId, @NonNull List<ParamCapability> updatedCaps) {
}
}
diff --git a/media/java/android/media/quality/ParamCapability.java b/media/java/android/media/quality/ParamCapability.java
index 70e85920c12f..0b698a9c1ad2 100644
--- a/media/java/android/media/quality/ParamCapability.java
+++ b/media/java/android/media/quality/ParamCapability.java
@@ -34,7 +34,7 @@ import java.lang.annotation.RetentionPolicy;
* @hide
*/
@FlaggedApi(Flags.FLAG_MEDIA_QUALITY_FW)
-public class ParamCapability implements Parcelable {
+public final class ParamCapability implements Parcelable {
/** @hide */
@IntDef(flag = true, prefix = { "TYPE_" }, value = {
@@ -104,6 +104,7 @@ public class ParamCapability implements Parcelable {
@NonNull
private final Bundle mCaps;
+ /** @hide */
protected ParamCapability(Parcel in) {
mName = in.readString();
mIsSupported = in.readBoolean();
@@ -112,7 +113,7 @@ public class ParamCapability implements Parcelable {
}
@Override
- public void writeToParcel(Parcel dest, int flags) {
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
dest.writeString(mName);
dest.writeBoolean(mIsSupported);
dest.writeInt(mType);
@@ -124,6 +125,7 @@ public class ParamCapability implements Parcelable {
return 0;
}
+ @NonNull
public static final Creator<ParamCapability> CREATOR = new Creator<ParamCapability>() {
@Override
public ParamCapability createFromParcel(Parcel in) {
diff --git a/media/java/android/media/quality/PictureProfile.java b/media/java/android/media/quality/PictureProfile.java
index 8fb57124d33e..2be47dd87ef2 100644
--- a/media/java/android/media/quality/PictureProfile.java
+++ b/media/java/android/media/quality/PictureProfile.java
@@ -71,6 +71,53 @@ public final class PictureProfile implements Parcelable {
*/
public static final int TYPE_APPLICATION = 2;
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(flag = false, prefix = "ERROR_", value = {
+ ERROR_UNKNOWN,
+ ERROR_NO_PERMISSION,
+ ERROR_DUPLICATE,
+ ERROR_INVALID_ARGUMENT,
+ ERROR_NOT_ALLOWLISTED
+ })
+ public @interface ErrorCode {}
+
+ /**
+ * Error code for unknown errors.
+ * @hide
+ */
+ public static final int ERROR_UNKNOWN = 0;
+
+ /**
+ * Error code for missing necessary permission to handle the profiles.
+ * @hide
+ */
+ public static final int ERROR_NO_PERMISSION = 1;
+
+ /**
+ * Error code for creating a profile with existing profile type and name.
+ *
+ * @see #getProfileType()
+ * @see #getName()
+ * @hide
+ */
+ public static final int ERROR_DUPLICATE = 2;
+
+ /**
+ * Error code for invalid argument.
+ * @hide
+ */
+ public static final int ERROR_INVALID_ARGUMENT = 3;
+
+ /**
+ * Error code for the case when an operation requires an allowlist but the caller is not in the
+ * list.
+ *
+ * @see MediaQualityManager#getPictureProfileAllowList()
+ * @hide
+ */
+ public static final int ERROR_NOT_ALLOWLISTED = 4;
+
private PictureProfile(@NonNull Parcel in) {
mId = in.readString();
diff --git a/nfc/api/system-current.txt b/nfc/api/system-current.txt
index 675c8f80add2..a23845fa17e9 100644
--- a/nfc/api/system-current.txt
+++ b/nfc/api/system-current.txt
@@ -100,6 +100,7 @@ package android.nfc {
method public void onHceEventReceived(int);
method public void onLaunchHceAppChooserActivity(@NonNull String, @NonNull java.util.List<android.nfc.cardemulation.ApduServiceInfo>, @NonNull android.content.ComponentName, @NonNull String);
method public void onLaunchHceTapAgainDialog(@NonNull android.nfc.cardemulation.ApduServiceInfo, @NonNull String);
+ method public void onLogEventNotified(@NonNull android.nfc.OemLogItems);
method public void onNdefMessage(@NonNull android.nfc.Tag, @NonNull android.nfc.NdefMessage, @NonNull java.util.function.Consumer<java.lang.Boolean>);
method public void onNdefRead(@NonNull java.util.function.Consumer<java.lang.Boolean>);
method public void onReaderOptionChanged(boolean);
@@ -115,6 +116,27 @@ package android.nfc {
method public int getNfceeId();
}
+ @FlaggedApi("android.nfc.nfc_oem_extension") public final class OemLogItems implements android.os.Parcelable {
+ method public int describeContents();
+ method public int getAction();
+ method public int getCallingPid();
+ method @Nullable public byte[] getCommandApdu();
+ method public int getEvent();
+ method @Nullable public byte[] getResponseApdu();
+ method @Nullable public java.time.Instant getRfFieldEventTimeMillis();
+ method @Nullable public android.nfc.Tag getTag();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.nfc.OemLogItems> CREATOR;
+ field public static final int EVENT_DISABLE = 2; // 0x2
+ field public static final int EVENT_ENABLE = 1; // 0x1
+ field public static final int EVENT_UNSET = 0; // 0x0
+ field public static final int LOG_ACTION_HCE_DATA = 516; // 0x204
+ field public static final int LOG_ACTION_NFC_TOGGLE = 513; // 0x201
+ field public static final int LOG_ACTION_RF_FIELD_STATE_CHANGED = 1; // 0x1
+ field public static final int LOG_ACTION_SCREEN_STATE_CHANGED = 518; // 0x206
+ field public static final int LOG_ACTION_TAG_DETECTED = 3; // 0x3
+ }
+
@FlaggedApi("android.nfc.nfc_oem_extension") public class RoutingStatus {
method @FlaggedApi("android.nfc.nfc_oem_extension") @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) public int getDefaultIsoDepRoute();
method @FlaggedApi("android.nfc.nfc_oem_extension") @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) public int getDefaultOffHostRoute();
diff --git a/nfc/java/android/nfc/INfcOemExtensionCallback.aidl b/nfc/java/android/nfc/INfcOemExtensionCallback.aidl
index 7f1fd15fe68a..b102e873d737 100644
--- a/nfc/java/android/nfc/INfcOemExtensionCallback.aidl
+++ b/nfc/java/android/nfc/INfcOemExtensionCallback.aidl
@@ -18,6 +18,7 @@ package android.nfc;
import android.content.ComponentName;
import android.nfc.cardemulation.ApduServiceInfo;
import android.nfc.NdefMessage;
+import android.nfc.OemLogItems;
import android.nfc.Tag;
import android.os.ResultReceiver;
@@ -51,4 +52,5 @@ interface INfcOemExtensionCallback {
void onNdefMessage(in Tag tag, in NdefMessage message, in ResultReceiver hasOemExecutableContent);
void onLaunchHceAppChooserActivity(in String selectedAid, in List<ApduServiceInfo> services, in ComponentName failedComponent, in String category);
void onLaunchHceTapAgainActivity(in ApduServiceInfo service, in String category);
+ void onLogEventNotified(in OemLogItems item);
}
diff --git a/nfc/java/android/nfc/NfcOemExtension.java b/nfc/java/android/nfc/NfcOemExtension.java
index 1bfe71461ac3..abd99bc02f55 100644
--- a/nfc/java/android/nfc/NfcOemExtension.java
+++ b/nfc/java/android/nfc/NfcOemExtension.java
@@ -392,6 +392,12 @@ public final class NfcOemExtension {
* @param category the category of the service
*/
void onLaunchHceTapAgainDialog(@NonNull ApduServiceInfo service, @NonNull String category);
+
+ /**
+ * Callback when OEM specified log event are notified.
+ * @param item the log items that contains log information of NFC event.
+ */
+ void onLogEventNotified(@NonNull OemLogItems item);
}
@@ -900,6 +906,12 @@ public final class NfcOemExtension {
handleVoid2ArgCallback(service, category, cb::onLaunchHceTapAgainDialog, ex));
}
+ @Override
+ public void onLogEventNotified(OemLogItems item) throws RemoteException {
+ mCallbackMap.forEach((cb, ex) ->
+ handleVoidCallback(item, cb::onLogEventNotified, ex));
+ }
+
private <T> void handleVoidCallback(
T input, Consumer<T> callbackMethod, Executor executor) {
synchronized (mLock) {
diff --git a/nfc/java/android/nfc/OemLogItems.aidl b/nfc/java/android/nfc/OemLogItems.aidl
new file mode 100644
index 000000000000..3bcb445fc7d2
--- /dev/null
+++ b/nfc/java/android/nfc/OemLogItems.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2024 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.nfc;
+
+parcelable OemLogItems; \ No newline at end of file
diff --git a/nfc/java/android/nfc/OemLogItems.java b/nfc/java/android/nfc/OemLogItems.java
new file mode 100644
index 000000000000..6671941c1cc9
--- /dev/null
+++ b/nfc/java/android/nfc/OemLogItems.java
@@ -0,0 +1,325 @@
+/*
+ * Copyright 2024 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.nfc;
+
+import android.annotation.FlaggedApi;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.time.Instant;
+
+/**
+ * A log class for OEMs to get log information of NFC events.
+ * @hide
+ */
+@FlaggedApi(Flags.FLAG_NFC_OEM_EXTENSION)
+@SystemApi
+public final class OemLogItems implements Parcelable {
+ /**
+ * Used when RF field state is changed.
+ */
+ public static final int LOG_ACTION_RF_FIELD_STATE_CHANGED = 0X01;
+ /**
+ * Used when NFC is toggled. Event should be set to {@link LogEvent#EVENT_ENABLE} or
+ * {@link LogEvent#EVENT_DISABLE} if this action is used.
+ */
+ public static final int LOG_ACTION_NFC_TOGGLE = 0x0201;
+ /**
+ * Used when sending host routing status.
+ */
+ public static final int LOG_ACTION_HCE_DATA = 0x0204;
+ /**
+ * Used when screen state is changed.
+ */
+ public static final int LOG_ACTION_SCREEN_STATE_CHANGED = 0x0206;
+ /**
+ * Used when tag is detected.
+ */
+ public static final int LOG_ACTION_TAG_DETECTED = 0x03;
+
+ /**
+ * @hide
+ */
+ @IntDef(prefix = { "LOG_ACTION_" }, value = {
+ LOG_ACTION_RF_FIELD_STATE_CHANGED,
+ LOG_ACTION_NFC_TOGGLE,
+ LOG_ACTION_HCE_DATA,
+ LOG_ACTION_SCREEN_STATE_CHANGED,
+ LOG_ACTION_TAG_DETECTED,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface LogAction {}
+
+ /**
+ * Represents the event is not set.
+ */
+ public static final int EVENT_UNSET = 0;
+ /**
+ * Represents nfc enable is called.
+ */
+ public static final int EVENT_ENABLE = 1;
+ /**
+ * Represents nfc disable is called.
+ */
+ public static final int EVENT_DISABLE = 2;
+ /** @hide */
+ @IntDef(prefix = { "EVENT_" }, value = {
+ EVENT_UNSET,
+ EVENT_ENABLE,
+ EVENT_DISABLE,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface LogEvent {}
+ private int mAction;
+ private int mEvent;
+ private int mCallingPid;
+ private byte[] mCommandApdus;
+ private byte[] mResponseApdus;
+ private Instant mRfFieldOnTime;
+ private Tag mTag;
+
+ /** @hide */
+ public OemLogItems(@LogAction int action, @LogEvent int event, int callingPid,
+ byte[] commandApdus, byte[] responseApdus, Instant rfFieldOnTime,
+ Tag tag) {
+ mAction = action;
+ mEvent = event;
+ mTag = tag;
+ mCallingPid = callingPid;
+ mCommandApdus = commandApdus;
+ mResponseApdus = responseApdus;
+ mRfFieldOnTime = rfFieldOnTime;
+ }
+
+ /**
+ * Describe the kinds of special objects contained in this Parcelable
+ * instance's marshaled representation. For example, if the object will
+ * include a file descriptor in the output of {@link #writeToParcel(Parcel, int)},
+ * the return value of this method must include the
+ * {@link #CONTENTS_FILE_DESCRIPTOR} bit.
+ *
+ * @return a bitmask indicating the set of special object types marshaled
+ * by this Parcelable object instance.
+ */
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * Flatten this object in to a Parcel.
+ *
+ * @param dest The Parcel in which the object should be written.
+ * @param flags Additional flags about how the object should be written.
+ * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
+ */
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(mAction);
+ dest.writeInt(mEvent);
+ dest.writeInt(mCallingPid);
+ dest.writeInt(mCommandApdus.length);
+ dest.writeByteArray(mCommandApdus);
+ dest.writeInt(mResponseApdus.length);
+ dest.writeByteArray(mResponseApdus);
+ dest.writeLong(mRfFieldOnTime.getEpochSecond());
+ dest.writeInt(mRfFieldOnTime.getNano());
+ dest.writeParcelable(mTag, 0);
+ }
+
+ /** @hide */
+ public static class Builder {
+ private final OemLogItems mItem;
+
+ public Builder(@LogAction int type) {
+ mItem = new OemLogItems(type, EVENT_UNSET, 0, new byte[0], new byte[0], null, null);
+ }
+
+ /** Setter of the log action. */
+ public OemLogItems.Builder setAction(@LogAction int action) {
+ mItem.mAction = action;
+ return this;
+ }
+
+ /** Setter of the log calling event. */
+ public OemLogItems.Builder setCallingEvent(@LogEvent int event) {
+ mItem.mEvent = event;
+ return this;
+ }
+
+ /** Setter of the log calling Pid. */
+ public OemLogItems.Builder setCallingPid(int pid) {
+ mItem.mCallingPid = pid;
+ return this;
+ }
+
+ /** Setter of APDU command. */
+ public OemLogItems.Builder setApduCommand(byte[] apdus) {
+ mItem.mCommandApdus = apdus;
+ return this;
+ }
+
+ /** Setter of RF field on time. */
+ public OemLogItems.Builder setRfFieldOnTime(Instant time) {
+ mItem.mRfFieldOnTime = time;
+ return this;
+ }
+
+ /** Setter of APDU response. */
+ public OemLogItems.Builder setApduResponse(byte[] apdus) {
+ mItem.mResponseApdus = apdus;
+ return this;
+ }
+
+ /** Setter of dispatched tag. */
+ public OemLogItems.Builder setTag(Tag tag) {
+ mItem.mTag = tag;
+ return this;
+ }
+
+ /** Builds an {@link OemLogItems} instance. */
+ public OemLogItems build() {
+ return mItem;
+ }
+ }
+
+ /**
+ * Gets the action of this log.
+ * @return one of {@link LogAction}
+ */
+ @LogAction
+ public int getAction() {
+ return mAction;
+ }
+
+ /**
+ * Gets the event of this log. This will be set to {@link LogEvent#EVENT_ENABLE} or
+ * {@link LogEvent#EVENT_DISABLE} only when action is set to
+ * {@link LogAction#LOG_ACTION_NFC_TOGGLE}
+ * @return one of {@link LogEvent}
+ */
+ @LogEvent
+ public int getEvent() {
+ return mEvent;
+ }
+
+ /**
+ * Gets the calling Pid of this log. This field will be set only when action is set to
+ * {@link LogAction#LOG_ACTION_NFC_TOGGLE}
+ * @return calling Pid
+ */
+ public int getCallingPid() {
+ return mCallingPid;
+ }
+
+ /**
+ * Gets the command APDUs of this log. This field will be set only when action is set to
+ * {@link LogAction#LOG_ACTION_HCE_DATA}
+ * @return a byte array of command APDUs with the same format as
+ * {@link android.nfc.cardemulation.HostApduService#sendResponseApdu(byte[])}
+ */
+ @Nullable
+ public byte[] getCommandApdu() {
+ return mCommandApdus;
+ }
+
+ /**
+ * Gets the response APDUs of this log. This field will be set only when action is set to
+ * {@link LogAction#LOG_ACTION_HCE_DATA}
+ * @return a byte array of response APDUs with the same format as
+ * {@link android.nfc.cardemulation.HostApduService#sendResponseApdu(byte[])}
+ */
+ @Nullable
+ public byte[] getResponseApdu() {
+ return mResponseApdus;
+ }
+
+ /**
+ * Gets the RF field event time in this log in millisecond. This field will be set only when
+ * action is set to {@link LogAction#LOG_ACTION_RF_FIELD_STATE_CHANGED}
+ * @return an {@link Instant} of RF field event time.
+ */
+ @Nullable
+ public Instant getRfFieldEventTimeMillis() {
+ return mRfFieldOnTime;
+ }
+
+ /**
+ * Gets the tag of this log. This field will be set only when action is set to
+ * {@link LogAction#LOG_ACTION_TAG_DETECTED}
+ * @return a detected {@link Tag} in {@link #LOG_ACTION_TAG_DETECTED} case. Return
+ * null otherwise.
+ */
+ @Nullable
+ public Tag getTag() {
+ return mTag;
+ }
+
+ private String byteToHex(byte[] bytes) {
+ char[] HexArray = "0123456789ABCDEF".toCharArray();
+ char[] hexChars = new char[bytes.length * 2];
+ for (int j = 0; j < bytes.length; j++) {
+ int v = bytes[j] & 0xFF;
+ hexChars[j * 2] = HexArray[v >>> 4];
+ hexChars[j * 2 + 1] = HexArray[v & 0x0F];
+ }
+ return new String(hexChars);
+ }
+
+ @Override
+ public String toString() {
+ return "[mCommandApdus: "
+ + ((mCommandApdus != null) ? byteToHex(mCommandApdus) : "null")
+ + "[mResponseApdus: "
+ + ((mResponseApdus != null) ? byteToHex(mResponseApdus) : "null")
+ + ", mCallingApi= " + mEvent
+ + ", mAction= " + mAction
+ + ", mCallingPId = " + mCallingPid
+ + ", mRfFieldOnTime= " + mRfFieldOnTime;
+ }
+ private OemLogItems(Parcel in) {
+ this.mAction = in.readInt();
+ this.mEvent = in.readInt();
+ this.mCallingPid = in.readInt();
+ this.mCommandApdus = new byte[in.readInt()];
+ in.readByteArray(this.mCommandApdus);
+ this.mResponseApdus = new byte[in.readInt()];
+ in.readByteArray(this.mResponseApdus);
+ this.mRfFieldOnTime = Instant.ofEpochSecond(in.readLong(), in.readInt());
+ this.mTag = in.readParcelable(Tag.class.getClassLoader(), Tag.class);
+ }
+
+ public static final @NonNull Parcelable.Creator<OemLogItems> CREATOR =
+ new Parcelable.Creator<OemLogItems>() {
+ @Override
+ public OemLogItems createFromParcel(Parcel in) {
+ return new OemLogItems(in);
+ }
+
+ @Override
+ public OemLogItems[] newArray(int size) {
+ return new OemLogItems[size];
+ }
+ };
+
+}
diff --git a/packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppPreference.java b/packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppPreference.java
index 3b52df7e5fbb..c3f6eb71c2e7 100644
--- a/packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppPreference.java
+++ b/packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppPreference.java
@@ -30,21 +30,28 @@ public class AppPreference extends Preference {
public AppPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
- setLayoutResource(R.layout.preference_app);
+ init(context);
}
public AppPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
- setLayoutResource(R.layout.preference_app);
+ init(context);
}
public AppPreference(Context context) {
super(context);
- setLayoutResource(R.layout.preference_app);
+ init(context);
}
public AppPreference(Context context, AttributeSet attrs) {
super(context, attrs);
- setLayoutResource(R.layout.preference_app);
+ init(context);
+ }
+
+ private void init(Context context) {
+ int resId = SettingsThemeHelper.isExpressiveTheme(context)
+ ? com.android.settingslib.widget.theme.R.layout.settingslib_expressive_preference
+ : R.layout.preference_app;
+ setLayoutResource(resId);
}
}
diff --git a/packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppSwitchPreference.java b/packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppSwitchPreference.java
index ecd500e1a160..3dcdfbaeb8b3 100644
--- a/packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppSwitchPreference.java
+++ b/packages/SettingsLib/AppPreference/src/com/android/settingslib/widget/AppSwitchPreference.java
@@ -32,22 +32,29 @@ public class AppSwitchPreference extends SwitchPreferenceCompat {
public AppSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
- setLayoutResource(R.layout.preference_app);
+ init(context);
}
public AppSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
- setLayoutResource(R.layout.preference_app);
+ init(context);
}
public AppSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
- setLayoutResource(R.layout.preference_app);
+ init(context);
}
public AppSwitchPreference(Context context) {
super(context);
- setLayoutResource(R.layout.preference_app);
+ init(context);
+ }
+
+ private void init(Context context) {
+ int resId = SettingsThemeHelper.isExpressiveTheme(context)
+ ? com.android.settingslib.widget.theme.R.layout.settingslib_expressive_preference
+ : R.layout.preference_app;
+ setLayoutResource(resId);
}
@Override
diff --git a/packages/SettingsLib/IntroPreference/Android.bp b/packages/SettingsLib/IntroPreference/Android.bp
index 155db186c702..8f9fb7a2e408 100644
--- a/packages/SettingsLib/IntroPreference/Android.bp
+++ b/packages/SettingsLib/IntroPreference/Android.bp
@@ -29,5 +29,6 @@ android_library {
min_sdk_version: "21",
apex_available: [
"//apex_available:platform",
+ "com.android.healthfitness",
],
}
diff --git a/packages/SettingsLib/SelectorWithWidgetPreference/Android.bp b/packages/SettingsLib/SelectorWithWidgetPreference/Android.bp
index 155ee831ae52..78e27fe5ad04 100644
--- a/packages/SettingsLib/SelectorWithWidgetPreference/Android.bp
+++ b/packages/SettingsLib/SelectorWithWidgetPreference/Android.bp
@@ -29,6 +29,7 @@ android_library {
"//apex_available:platform",
"com.android.permission",
"com.android.mediaprovider",
+ "com.android.healthfitness",
],
}
@@ -51,5 +52,6 @@ java_aconfig_library {
"//apex_available:platform",
"com.android.permission",
"com.android.mediaprovider",
+ "com.android.healthfitness",
],
}
diff --git a/packages/SettingsLib/SettingsTheme/res/layout-v35/settingslib_expressive_preference_icon_frame.xml b/packages/SettingsLib/SettingsTheme/res/layout-v35/settingslib_expressive_preference_icon_frame.xml
index ccdf37d452b0..0cd0b3cb14f1 100644
--- a/packages/SettingsLib/SettingsTheme/res/layout-v35/settingslib_expressive_preference_icon_frame.xml
+++ b/packages/SettingsLib/SettingsTheme/res/layout-v35/settingslib_expressive_preference_icon_frame.xml
@@ -22,7 +22,7 @@
android:minWidth="@dimen/settingslib_expressive_space_medium3"
android:minHeight="@dimen/settingslib_expressive_space_medium3"
android:gravity="center"
- android:layout_marginEnd="-8dp"
+ android:layout_marginEnd="-4dp"
android:filterTouchesWhenObscured="false">
<androidx.preference.internal.PreferenceImageView
diff --git a/packages/SettingsLib/SettingsTheme/res/values-v35/styles_preference_expressive.xml b/packages/SettingsLib/SettingsTheme/res/values-v35/styles_preference_expressive.xml
index 3c69027c2080..cec8e45e2bfb 100644
--- a/packages/SettingsLib/SettingsTheme/res/values-v35/styles_preference_expressive.xml
+++ b/packages/SettingsLib/SettingsTheme/res/values-v35/styles_preference_expressive.xml
@@ -36,33 +36,34 @@
<style name="SettingsLibPreference.SwitchPreference" parent="SettingsSwitchPreference.SettingsLib"/>
<style name="SettingsLibPreference.Expressive">
- <item name="android:layout">@layout/settingslib_expressive_preference</item>
+ <item name="layout">@layout/settingslib_expressive_preference</item>
</style>
<style name="SettingsLibPreference.Category.Expressive">
</style>
<style name="SettingsLibPreference.CheckBoxPreference.Expressive">
- <item name="android:layout">@layout/settingslib_expressive_preference</item>
+ <item name="layout">@layout/settingslib_expressive_preference</item>
</style>
<style name="SettingsLibPreference.SwitchPreferenceCompat.Expressive">
- <item name="android:layout">@layout/settingslib_expressive_preference</item>
+ <item name="layout">@layout/settingslib_expressive_preference</item>
<item name="android:widgetLayout">@layout/settingslib_expressive_preference_switch</item>
</style>
<style name="SettingsLibPreference.SeekBarPreference.Expressive"/>
<style name="SettingsLibPreference.PreferenceScreen.Expressive">
- <item name="android:layout">@layout/settingslib_expressive_preference</item>
+ <item name="layout">@layout/settingslib_expressive_preference</item>
</style>
<style name="SettingsLibPreference.DialogPreference.Expressive">
+ <item name="layout">@layout/settingslib_expressive_preference</item>
</style>
<style name="SettingsLibPreference.DialogPreference.EditTextPreference.Expressive">
- <item name="android:layout">@layout/settingslib_expressive_preference</item>
- <item name="android:dialogLayout">@layout/settingslib_preference_dialog_edittext</item>
+ <item name="layout">@layout/settingslib_expressive_preference</item>
+ <item name="dialogLayout">@layout/settingslib_preference_dialog_edittext</item>
</style>
<style name="SettingsLibPreference.DropDown.Expressive">
diff --git a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
index 064198fc5e46..927a1c59cc76 100644
--- a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
+++ b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
@@ -284,5 +284,6 @@ public class SecureSettings {
Settings.Secure.MANDATORY_BIOMETRICS,
Settings.Secure.MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED,
Settings.Secure.ADVANCED_PROTECTION_MODE,
+ Settings.Secure.ACCESSIBILITY_KEY_GESTURE_TARGETS,
};
}
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
index c002a04d5b11..6d73ee27f076 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
@@ -332,6 +332,9 @@ public class SecureSettingsValidators {
VALIDATORS.put(
Secure.ACCESSIBILITY_QS_TARGETS,
ACCESSIBILITY_SHORTCUT_TARGET_LIST_VALIDATOR);
+ VALIDATORS.put(
+ Secure.ACCESSIBILITY_KEY_GESTURE_TARGETS,
+ ACCESSIBILITY_SHORTCUT_TARGET_LIST_VALIDATOR);
VALIDATORS.put(Secure.ACCESSIBILITY_FORCE_INVERT_COLOR_ENABLED, BOOLEAN_VALIDATOR);
VALIDATORS.put(Secure.ONE_HANDED_MODE_ACTIVATED, BOOLEAN_VALIDATOR);
VALIDATORS.put(Secure.ONE_HANDED_MODE_ENABLED, BOOLEAN_VALIDATOR);
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 2034f36c558b..fb0aaf8e5ae1 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -1823,6 +1823,9 @@ class SettingsProtoDumpUtil {
Settings.Secure.ACCESSIBILITY_QS_TARGETS,
SecureSettingsProto.Accessibility.QS_TARGETS);
dumpSetting(s, p,
+ Settings.Secure.ACCESSIBILITY_KEY_GESTURE_TARGETS,
+ SecureSettingsProto.Accessibility.ACCESSIBILITY_KEY_GESTURE_TARGETS);
+ dumpSetting(s, p,
Settings.Secure.ACCESSIBILITY_MAGNIFICATION_CAPABILITY,
SecureSettingsProto.Accessibility.ACCESSIBILITY_MAGNIFICATION_CAPABILITY);
dumpSetting(s, p,
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 0724410a2954..7b6321d1cc7d 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -962,6 +962,10 @@
<!-- Permission required for ExecutableMethodFileOffsetsTest -->
<uses-permission android:name="android.permission.DYNAMIC_INSTRUMENTATION" />
+ <!-- Permissions required for CTS test - SettingsPreferenceServiceClientTest -->
+ <uses-permission android:name="android.permission.READ_SYSTEM_PREFERENCES" />
+ <uses-permission android:name="android.permission.WRITE_SYSTEM_PREFERENCES" />
+
<application
android:label="@string/app_label"
android:theme="@android:style/Theme.DeviceDefault.DayNight"
diff --git a/packages/Shell/src/com/android/shell/BugreportProgressService.java b/packages/Shell/src/com/android/shell/BugreportProgressService.java
index b4d81d6937ed..7c478ac78a29 100644
--- a/packages/Shell/src/com/android/shell/BugreportProgressService.java
+++ b/packages/Shell/src/com/android/shell/BugreportProgressService.java
@@ -353,7 +353,7 @@ public class BugreportProgressService extends Service {
public void onDestroy() {
mServiceHandler.getLooper().quit();
mScreenshotHandler.getLooper().quit();
- mBugreportSingleThreadExecutor.close();
+ mBugreportSingleThreadExecutor.shutdown();
super.onDestroy();
}
diff --git a/packages/SystemUI/README.md b/packages/SystemUI/README.md
index 2910bba71341..635a97ef8a47 100644
--- a/packages/SystemUI/README.md
+++ b/packages/SystemUI/README.md
@@ -87,7 +87,7 @@ immediately for any callbacks added.
There are a few places where CommandQueue is used as a bus to communicate
across sysui. Such as when StatusBar calls CommandQueue#recomputeDisableFlags.
-This is generally used a shortcut to directly trigger CommandQueue rather than
+This is generally used as a shortcut to directly trigger CommandQueue rather than
calling StatusManager and waiting for the call to come back to IStatusBar.
### [com.android.systemui.util.NotificationChannels](/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java)
diff --git a/packages/SystemUI/aconfig/systemui.aconfig b/packages/SystemUI/aconfig/systemui.aconfig
index 02b7667dc820..207ed71c955d 100644
--- a/packages/SystemUI/aconfig/systemui.aconfig
+++ b/packages/SystemUI/aconfig/systemui.aconfig
@@ -16,6 +16,16 @@ flag {
}
flag {
+ name: "multiuser_wifi_picker_tracker_support"
+ namespace: "systemui"
+ description: "Adds WifiPickerTracker support for multiple users to support when HSUM is enabled."
+ bug: "371586248"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
+flag {
name: "udfps_view_performance"
namespace: "systemui"
description: "Decrease screen off blocking calls by waiting until the device is finished going to sleep before adding the udfps view."
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/statusbar/phone/SystemUIDialogFactoryExt.kt b/packages/SystemUI/compose/features/src/com/android/systemui/statusbar/phone/SystemUIDialogFactoryExt.kt
index eeab232542c0..163f4b36f472 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/statusbar/phone/SystemUIDialogFactoryExt.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/statusbar/phone/SystemUIDialogFactoryExt.kt
@@ -59,6 +59,7 @@ import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.hideFromAccessibility
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
@@ -286,7 +287,10 @@ private fun DragHandle(dialog: Dialog) {
Surface(
modifier =
Modifier.padding(top = 16.dp, bottom = 6.dp)
- .semantics { contentDescription = dragHandleContentDescription }
+ .semantics {
+ contentDescription = dragHandleContentDescription
+ hideFromAccessibility()
+ }
.clickable { dialog.dismiss() },
color = MaterialTheme.colorScheme.onSurfaceVariant,
shape = MaterialTheme.shapes.extraLarge,
diff --git a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/Element.kt b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/Element.kt
index e7b66c5f0d2f..d976e8e62f3c 100644
--- a/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/Element.kt
+++ b/packages/SystemUI/compose/scene/src/com/android/compose/animation/scene/Element.kt
@@ -693,8 +693,8 @@ private fun prepareInterruption(
val fromState = updateStateInContent(transition.fromContent)
val toState = updateStateInContent(transition.toContent)
- reconcileStates(element, previousTransition)
- reconcileStates(element, transition)
+ val previousUniqueState = reconcileStates(element, previousTransition, previousState = null)
+ reconcileStates(element, transition, previousState = previousUniqueState)
// Remove the interruption values to all contents but the content(s) where the element will be
// placed, to make sure that interruption deltas are computed only right after this interruption
@@ -721,12 +721,32 @@ private fun prepareInterruption(
/**
* Reconcile the state of [element] in the formContent and toContent of [transition] so that the
* values before interruption have their expected values, taking shared transitions into account.
+ *
+ * @return the unique state this element had during [transition], `null` if it had multiple
+ * different states (i.e. the shared animation was disabled).
*/
-private fun reconcileStates(element: Element, transition: TransitionState.Transition) {
- val fromContentState = element.stateByContent[transition.fromContent] ?: return
- val toContentState = element.stateByContent[transition.toContent] ?: return
+private fun reconcileStates(
+ element: Element,
+ transition: TransitionState.Transition,
+ previousState: Element.State?,
+): Element.State? {
+ fun reconcileWithPreviousState(state: Element.State) {
+ if (previousState != null && state.offsetBeforeInterruption == Offset.Unspecified) {
+ state.updateValuesBeforeInterruption(previousState)
+ }
+ }
+
+ val fromContentState = element.stateByContent[transition.fromContent]
+ val toContentState = element.stateByContent[transition.toContent]
+
+ if (fromContentState == null || toContentState == null) {
+ return (fromContentState ?: toContentState)
+ ?.also { reconcileWithPreviousState(it) }
+ ?.takeIf { it.offsetBeforeInterruption != Offset.Unspecified }
+ }
+
if (!isSharedElementEnabled(element.key, transition)) {
- return
+ return null
}
if (
@@ -735,13 +755,19 @@ private fun reconcileStates(element: Element, transition: TransitionState.Transi
) {
// Element is shared and placed in fromContent only.
toContentState.updateValuesBeforeInterruption(fromContentState)
- } else if (
+ return fromContentState
+ }
+
+ if (
toContentState.offsetBeforeInterruption != Offset.Unspecified &&
fromContentState.offsetBeforeInterruption == Offset.Unspecified
) {
// Element is shared and placed in toContent only.
fromContentState.updateValuesBeforeInterruption(toContentState)
+ return toContentState
}
+
+ return null
}
private fun Element.State.selfUpdateValuesBeforeInterruption() {
diff --git a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/ElementTest.kt b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/ElementTest.kt
index 4a9051598ddc..a301856d024f 100644
--- a/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/ElementTest.kt
+++ b/packages/SystemUI/compose/scene/tests/src/com/android/compose/animation/scene/ElementTest.kt
@@ -2638,4 +2638,58 @@ class ElementTest {
assertWithMessage("Frame $i didn't replace Foo").that(numberOfPlacements).isEqualTo(0)
}
}
+
+ @Test
+ fun interruption_considerPreviousUniqueState() {
+ @Composable
+ fun SceneScope.Foo(modifier: Modifier = Modifier) {
+ Box(modifier.element(TestElements.Foo).size(50.dp))
+ }
+
+ val state = rule.runOnUiThread { MutableSceneTransitionLayoutState(SceneA) }
+ val scope =
+ rule.setContentAndCreateMainScope {
+ SceneTransitionLayout(state) {
+ scene(SceneA) { Box(Modifier.fillMaxSize()) { Foo() } }
+ scene(SceneB) { Box(Modifier.fillMaxSize()) }
+ scene(SceneC) {
+ Box(Modifier.fillMaxSize()) { Foo(Modifier.offset(x = 100.dp, y = 100.dp)) }
+ }
+ }
+ }
+
+ // During A => B, Foo disappears and stays in its original position.
+ scope.launch { state.startTransition(transition(SceneA, SceneB)) }
+ rule
+ .onNode(isElement(TestElements.Foo))
+ .assertSizeIsEqualTo(50.dp)
+ .assertPositionInRootIsEqualTo(0.dp, 0.dp)
+
+ // Interrupt A => B by B => C.
+ var interruptionProgress by mutableFloatStateOf(1f)
+ scope.launch {
+ state.startTransition(
+ transition(SceneB, SceneC, interruptionProgress = { interruptionProgress })
+ )
+ }
+
+ // During B => C, Foo appears again. It is still at (0, 0) when the interruption progress is
+ // 100%, and converges to its position (100, 100) in C.
+ rule
+ .onNode(isElement(TestElements.Foo))
+ .assertSizeIsEqualTo(50.dp)
+ .assertPositionInRootIsEqualTo(0.dp, 0.dp)
+
+ interruptionProgress = 0.5f
+ rule
+ .onNode(isElement(TestElements.Foo))
+ .assertSizeIsEqualTo(50.dp)
+ .assertPositionInRootIsEqualTo(50.dp, 50.dp)
+
+ interruptionProgress = 0f
+ rule
+ .onNode(isElement(TestElements.Foo))
+ .assertSizeIsEqualTo(50.dp)
+ .assertPositionInRootIsEqualTo(100.dp, 100.dp)
+ }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorTest.kt
index 160865d625f5..38ed22a1c410 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorTest.kt
@@ -17,6 +17,8 @@
package com.android.systemui.deviceentry.domain.interactor
import android.content.pm.UserInfo
+import android.os.PowerManager
+import android.provider.Settings
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.internal.widget.LockPatternUtils
@@ -31,11 +33,8 @@ import com.android.systemui.flags.fakeSystemPropertiesHelper
import com.android.systemui.keyguard.data.repository.fakeBiometricSettingsRepository
import com.android.systemui.keyguard.data.repository.fakeDeviceEntryFaceAuthRepository
import com.android.systemui.keyguard.data.repository.fakeDeviceEntryFingerprintAuthRepository
-import com.android.systemui.keyguard.data.repository.fakeKeyguardTransitionRepository
import com.android.systemui.keyguard.data.repository.fakeTrustRepository
-import com.android.systemui.keyguard.domain.interactor.keyguardTransitionInteractor
import com.android.systemui.keyguard.shared.model.AuthenticationFlags
-import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.keyguard.shared.model.SuccessFingerprintAuthenticationStatus
import com.android.systemui.kosmos.testScope
import com.android.systemui.power.domain.interactor.PowerInteractor.Companion.setAsleepForTest
@@ -44,9 +43,12 @@ import com.android.systemui.power.domain.interactor.powerInteractor
import com.android.systemui.testKosmos
import com.android.systemui.user.data.model.SelectionStatus
import com.android.systemui.user.data.repository.fakeUserRepository
+import com.android.systemui.user.domain.interactor.selectedUserInteractor
+import com.android.systemui.util.settings.fakeSettings
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Before
@@ -228,6 +230,12 @@ class DeviceUnlockedInteractorTest : SysuiTestCase() {
@Test
fun deviceUnlockStatus_isResetToFalse_whenDeviceGoesToSleep() =
testScope.runTest {
+ kosmos.fakeSettings.putIntForUser(
+ Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
+ 0,
+ kosmos.selectedUserInteractor.getSelectedUserId(),
+ )
+ kosmos.fakeAuthenticationRepository.powerButtonInstantlyLocks = false
val deviceUnlockStatus by collectLastValue(underTest.deviceUnlockStatus)
kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
@@ -243,35 +251,66 @@ class DeviceUnlockedInteractorTest : SysuiTestCase() {
}
@Test
- fun deviceUnlockStatus_becomesUnlocked_whenFingerprintUnlocked_whileDeviceAsleepInAod() =
+ fun deviceUnlockStatus_isResetToFalse_whenDeviceGoesToSleep_afterDelay() =
testScope.runTest {
+ val delay = 5000
+ kosmos.fakeSettings.putIntForUser(
+ Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
+ delay,
+ kosmos.selectedUserInteractor.getSelectedUserId(),
+ )
+ kosmos.fakeAuthenticationRepository.powerButtonInstantlyLocks = false
val deviceUnlockStatus by collectLastValue(underTest.deviceUnlockStatus)
- assertThat(deviceUnlockStatus?.isUnlocked).isFalse()
- kosmos.fakeKeyguardTransitionRepository.sendTransitionSteps(
- from = KeyguardState.LOCKSCREEN,
- to = KeyguardState.AOD,
- testScope = this,
+ kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
+ SuccessFingerprintAuthenticationStatus(0, true)
)
+ runCurrent()
+ assertThat(deviceUnlockStatus?.isUnlocked).isTrue()
+
kosmos.powerInteractor.setAsleepForTest()
runCurrent()
+ assertThat(deviceUnlockStatus?.isUnlocked).isTrue()
+ advanceTimeBy(delay.toLong())
assertThat(deviceUnlockStatus?.isUnlocked).isFalse()
+ }
+
+ @Test
+ fun deviceUnlockStatus_isResetToFalse_whenDeviceGoesToSleep_powerButtonLocksInstantly() =
+ testScope.runTest {
+ kosmos.fakeSettings.putIntForUser(
+ Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
+ 5000,
+ kosmos.selectedUserInteractor.getSelectedUserId(),
+ )
+ kosmos.fakeAuthenticationRepository.powerButtonInstantlyLocks = true
+ val deviceUnlockStatus by collectLastValue(underTest.deviceUnlockStatus)
kosmos.fakeDeviceEntryFingerprintAuthRepository.setAuthenticationStatus(
SuccessFingerprintAuthenticationStatus(0, true)
)
runCurrent()
assertThat(deviceUnlockStatus?.isUnlocked).isTrue()
+
+ kosmos.powerInteractor.setAsleepForTest(
+ sleepReason = PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON
+ )
+ runCurrent()
+
+ assertThat(deviceUnlockStatus?.isUnlocked).isFalse()
}
@Test
- fun deviceUnlockStatus_staysLocked_whenFingerprintUnlocked_whileDeviceAsleep() =
+ fun deviceUnlockStatus_becomesUnlocked_whenFingerprintUnlocked_whileDeviceAsleep() =
testScope.runTest {
+ kosmos.fakeSettings.putIntForUser(
+ Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
+ 0,
+ kosmos.selectedUserInteractor.getSelectedUserId(),
+ )
val deviceUnlockStatus by collectLastValue(underTest.deviceUnlockStatus)
assertThat(deviceUnlockStatus?.isUnlocked).isFalse()
- assertThat(kosmos.keyguardTransitionInteractor.getCurrentState())
- .isEqualTo(KeyguardState.LOCKSCREEN)
kosmos.powerInteractor.setAsleepForTest()
runCurrent()
@@ -282,7 +321,7 @@ class DeviceUnlockedInteractorTest : SysuiTestCase() {
SuccessFingerprintAuthenticationStatus(0, true)
)
runCurrent()
- assertThat(deviceUnlockStatus?.isUnlocked).isFalse()
+ assertThat(deviceUnlockStatus?.isUnlocked).isTrue()
}
@Test
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardOcclusionInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardOcclusionInteractorTest.kt
index 8914c80cdd5e..ae2a5c5fe501 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardOcclusionInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/domain/interactor/KeyguardOcclusionInteractorTest.kt
@@ -34,6 +34,7 @@
package com.android.systemui.keyguard.domain.interactor
+import android.provider.Settings
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
@@ -43,6 +44,7 @@ import com.android.systemui.coroutines.collectLastValue
import com.android.systemui.coroutines.collectValues
import com.android.systemui.flags.DisableSceneContainer
import com.android.systemui.flags.EnableSceneContainer
+import com.android.systemui.keyguard.KeyguardViewMediator
import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
import com.android.systemui.keyguard.data.repository.deviceEntryFingerprintAuthRepository
import com.android.systemui.keyguard.data.repository.fakeKeyguardTransitionRepository
@@ -60,10 +62,13 @@ import com.android.systemui.scene.data.repository.setSceneTransition
import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.statusbar.domain.interactor.keyguardOcclusionInteractor
import com.android.systemui.testKosmos
+import com.android.systemui.util.settings.data.repository.userAwareSecureSettingsRepository
import com.google.common.truth.Truth.assertThat
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Before
@@ -96,7 +101,7 @@ class KeyguardOcclusionInteractorTest : SysuiTestCase() {
from = KeyguardState.LOCKSCREEN,
to = KeyguardState.AOD,
testScope = testScope,
- throughTransitionState = TransitionState.RUNNING
+ throughTransitionState = TransitionState.RUNNING,
)
powerInteractor.onCameraLaunchGestureDetected()
@@ -134,7 +139,7 @@ class KeyguardOcclusionInteractorTest : SysuiTestCase() {
from = KeyguardState.AOD,
to = KeyguardState.LOCKSCREEN,
testScope = testScope,
- throughTransitionState = TransitionState.RUNNING
+ throughTransitionState = TransitionState.RUNNING,
)
powerInteractor.onCameraLaunchGestureDetected()
@@ -182,21 +187,12 @@ class KeyguardOcclusionInteractorTest : SysuiTestCase() {
kosmos.keyguardOcclusionRepository.setShowWhenLockedActivityInfo(true)
runCurrent()
- assertThat(values)
- .containsExactly(
- false,
- true,
- )
+ assertThat(values).containsExactly(false, true)
kosmos.keyguardOcclusionRepository.setShowWhenLockedActivityInfo(false)
runCurrent()
- assertThat(values)
- .containsExactly(
- false,
- true,
- false,
- )
+ assertThat(values).containsExactly(false, true, false)
kosmos.keyguardOcclusionRepository.setShowWhenLockedActivityInfo(true)
runCurrent()
@@ -228,7 +224,7 @@ class KeyguardOcclusionInteractorTest : SysuiTestCase() {
from = KeyguardState.GONE,
to = KeyguardState.AOD,
testScope = testScope,
- throughTransitionState = TransitionState.RUNNING
+ throughTransitionState = TransitionState.RUNNING,
)
powerInteractor.onCameraLaunchGestureDetected()
@@ -242,10 +238,7 @@ class KeyguardOcclusionInteractorTest : SysuiTestCase() {
testScope = testScope,
)
- assertThat(values)
- .containsExactly(
- false,
- )
+ assertThat(values).containsExactly(false)
}
@Test
@@ -263,7 +256,7 @@ class KeyguardOcclusionInteractorTest : SysuiTestCase() {
from = KeyguardState.UNDEFINED,
to = KeyguardState.AOD,
testScope = testScope,
- throughTransitionState = TransitionState.RUNNING
+ throughTransitionState = TransitionState.RUNNING,
)
powerInteractor.onCameraLaunchGestureDetected()
@@ -278,10 +271,7 @@ class KeyguardOcclusionInteractorTest : SysuiTestCase() {
testScope = testScope,
)
- assertThat(values)
- .containsExactly(
- false,
- )
+ assertThat(values).containsExactly(false)
}
@Test
@@ -304,8 +294,19 @@ class KeyguardOcclusionInteractorTest : SysuiTestCase() {
assertThat(occludingActivityWillDismissKeyguard).isTrue()
// Re-lock device:
- kosmos.powerInteractor.setAsleepForTest()
- runCurrent()
+ lockDevice()
assertThat(occludingActivityWillDismissKeyguard).isFalse()
}
+
+ private suspend fun TestScope.lockDevice() {
+ kosmos.powerInteractor.setAsleepForTest()
+ advanceTimeBy(
+ kosmos.userAwareSecureSettingsRepository
+ .getInt(
+ Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
+ KeyguardViewMediator.KEYGUARD_LOCK_AFTER_DELAY_DEFAULT,
+ )
+ .toLong()
+ )
+ }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryTest.kt
index 8e67e602abd9..f8f6fe246563 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryTest.kt
@@ -38,6 +38,7 @@ import com.android.systemui.media.controls.util.fakeMediaControllerFactory
import com.android.systemui.media.controls.util.fakeSessionTokenFactory
import com.android.systemui.res.R
import com.android.systemui.testKosmos
+import com.android.systemui.util.concurrency.execution
import com.google.common.collect.ImmutableList
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.test.runCurrent
@@ -105,6 +106,7 @@ class Media3ActionFactoryTest : SysuiTestCase() {
kosmos.looper,
handler,
kosmos.testScope,
+ kosmos.execution,
)
controllerFactory.setMedia3Controller(media3Controller)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryTest.kt
index dda9cd5529a5..4dcbdfae6d4a 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryTest.kt
@@ -104,67 +104,6 @@ class QSPreferencesRepositoryTest : SysuiTestCase() {
}
}
- @Test
- fun showLabels_updatesFromSharedPreferences() =
- with(kosmos) {
- testScope.runTest {
- val latest by collectLastValue(underTest.showLabels)
- assertThat(latest).isFalse()
-
- setShowLabelsInSharedPreferences(true)
- assertThat(latest).isTrue()
-
- setShowLabelsInSharedPreferences(false)
- assertThat(latest).isFalse()
- }
- }
-
- @Test
- fun showLabels_updatesFromUserChange() =
- with(kosmos) {
- testScope.runTest {
- fakeUserRepository.setUserInfos(USERS)
- val latest by collectLastValue(underTest.showLabels)
-
- fakeUserRepository.setSelectedUserInfo(PRIMARY_USER)
- setShowLabelsInSharedPreferences(false)
-
- fakeUserRepository.setSelectedUserInfo(ANOTHER_USER)
- setShowLabelsInSharedPreferences(true)
-
- fakeUserRepository.setSelectedUserInfo(PRIMARY_USER)
- assertThat(latest).isFalse()
- }
- }
-
- @Test
- fun setShowLabels_inSharedPreferences() {
- underTest.setShowLabels(false)
- assertThat(getShowLabelsFromSharedPreferences(true)).isFalse()
-
- underTest.setShowLabels(true)
- assertThat(getShowLabelsFromSharedPreferences(false)).isTrue()
- }
-
- @Test
- fun setShowLabels_forDifferentUser() =
- with(kosmos) {
- testScope.runTest {
- fakeUserRepository.setUserInfos(USERS)
-
- fakeUserRepository.setSelectedUserInfo(PRIMARY_USER)
- underTest.setShowLabels(false)
- assertThat(getShowLabelsFromSharedPreferences(true)).isFalse()
-
- fakeUserRepository.setSelectedUserInfo(ANOTHER_USER)
- underTest.setShowLabels(true)
- assertThat(getShowLabelsFromSharedPreferences(false)).isTrue()
-
- fakeUserRepository.setSelectedUserInfo(PRIMARY_USER)
- assertThat(getShowLabelsFromSharedPreferences(true)).isFalse()
- }
- }
-
private fun getSharedPreferences(): SharedPreferences =
with(kosmos) {
return userFileManager.getSharedPreferences(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/QuickAccessWalletTileTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/QuickAccessWalletTileTest.java
index 0729e2fcd35f..03c1f92aad4c 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/QuickAccessWalletTileTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/QuickAccessWalletTileTest.java
@@ -93,6 +93,8 @@ public class QuickAccessWalletTileTest extends SysuiTestCase {
private static final String CARD_DESCRIPTION = "•••• 1234";
private static final Icon CARD_IMAGE =
Icon.createWithBitmap(Bitmap.createBitmap(70, 50, Bitmap.Config.ARGB_8888));
+ private static final Icon INVALID_CARD_IMAGE =
+ Icon.createWithContentUri("content://media/external/images/media");
private static final int PRIMARY_USER_ID = 0;
private static final int SECONDARY_USER_ID = 10;
@@ -444,6 +446,14 @@ public class QuickAccessWalletTileTest extends SysuiTestCase {
}
@Test
+ public void testQueryCards_invalidDrawable_noSideViewDrawable() {
+ when(mKeyguardStateController.isUnlocked()).thenReturn(true);
+ setUpInvalidWalletCard(/* hasCard= */ true);
+
+ assertNull(mTile.getState().sideViewCustomDrawable);
+ }
+
+ @Test
public void testQueryCards_error_notUpdateSideViewDrawable() {
String errorMessage = "getWalletCardsError";
GetWalletCardsError error = new GetWalletCardsError(CARD_IMAGE, errorMessage);
@@ -503,9 +513,33 @@ public class QuickAccessWalletTileTest extends SysuiTestCase {
mTestableLooper.processAllMessages();
}
+ private void setUpInvalidWalletCard(boolean hasCard) {
+ GetWalletCardsResponse response =
+ new GetWalletCardsResponse(
+ hasCard
+ ? Collections.singletonList(createInvalidWalletCard(mContext))
+ : Collections.EMPTY_LIST, 0);
+
+ mTile.handleSetListening(true);
+
+ verify(mController).queryWalletCards(mCallbackCaptor.capture());
+
+ mCallbackCaptor.getValue().onWalletCardsRetrieved(response);
+ mTestableLooper.processAllMessages();
+ }
+
private WalletCard createWalletCard(Context context) {
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 0, mWalletIntent, PendingIntent.FLAG_IMMUTABLE);
return new WalletCard.Builder(CARD_ID, CARD_IMAGE, CARD_DESCRIPTION, pendingIntent).build();
}
+
+ private WalletCard createInvalidWalletCard(Context context) {
+ PendingIntent pendingIntent =
+ PendingIntent.getActivity(context, 0, mWalletIntent, PendingIntent.FLAG_IMMUTABLE);
+ return new WalletCard.Builder(
+ CARD_ID, INVALID_CARD_IMAGE, CARD_DESCRIPTION, pendingIntent).build();
+ }
+
+
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
index 3be8a380b191..b5f005cdc706 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/SceneFrameworkIntegrationTest.kt
@@ -18,6 +18,7 @@
package com.android.systemui.scene
+import android.provider.Settings
import android.telephony.TelephonyManager
import android.testing.TestableLooper.RunWithLooper
import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -42,6 +43,7 @@ import com.android.systemui.deviceentry.domain.interactor.deviceEntryInteractor
import com.android.systemui.flags.EnableSceneContainer
import com.android.systemui.flags.Flags
import com.android.systemui.flags.fakeFeatureFlagsClassic
+import com.android.systemui.keyguard.KeyguardViewMediator
import com.android.systemui.keyguard.ui.viewmodel.lockscreenUserActionsViewModel
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.collectLastValue
@@ -64,6 +66,7 @@ import com.android.systemui.telephony.data.repository.fakeTelephonyRepository
import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.whenever
+import com.android.systemui.util.settings.data.repository.userAwareSecureSettingsRepository
import com.android.telecom.mockTelecomManager
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
@@ -72,6 +75,7 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import org.junit.Before
import org.junit.Test
@@ -541,7 +545,14 @@ class SceneFrameworkIntegrationTest : SysuiTestCase() {
.isTrue()
powerInteractor.setAsleepForTest()
- testScope.runCurrent()
+ testScope.advanceTimeBy(
+ kosmos.userAwareSecureSettingsRepository
+ .getInt(
+ Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
+ KeyguardViewMediator.KEYGUARD_LOCK_AFTER_DELAY_DEFAULT,
+ )
+ .toLong()
+ )
powerInteractor.setAwakeForTest()
testScope.runCurrent()
@@ -631,14 +642,25 @@ class SceneFrameworkIntegrationTest : SysuiTestCase() {
}
/** Changes device wakefulness state from awake to asleep, going through intermediary states. */
- private fun Kosmos.putDeviceToSleep() {
+ private suspend fun Kosmos.putDeviceToSleep(waitForLock: Boolean = true) {
val wakefulnessModel = powerInteractor.detailedWakefulness.value
assertWithMessage("Cannot put device to sleep as it's already asleep!")
.that(wakefulnessModel.isAwake())
.isTrue()
powerInteractor.setAsleepForTest()
- testScope.runCurrent()
+ if (waitForLock) {
+ testScope.advanceTimeBy(
+ kosmos.userAwareSecureSettingsRepository
+ .getInt(
+ Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
+ KeyguardViewMediator.KEYGUARD_LOCK_AFTER_DELAY_DEFAULT,
+ )
+ .toLong()
+ )
+ } else {
+ testScope.runCurrent()
+ }
}
/** Emulates the dismissal of the IME (soft keyboard). */
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
index 55f88cc5b7a2..152911a30524 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
@@ -23,6 +23,7 @@ import android.hardware.face.FaceManager
import android.os.PowerManager
import android.platform.test.annotations.DisableFlags
import android.platform.test.annotations.EnableFlags
+import android.provider.Settings
import android.view.Display
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
@@ -59,6 +60,7 @@ import com.android.systemui.flags.EnableSceneContainer
import com.android.systemui.haptics.msdl.fakeMSDLPlayer
import com.android.systemui.haptics.vibratorHelper
import com.android.systemui.keyevent.data.repository.fakeKeyEventRepository
+import com.android.systemui.keyguard.KeyguardViewMediator
import com.android.systemui.keyguard.data.repository.biometricSettingsRepository
import com.android.systemui.keyguard.data.repository.deviceEntryFingerprintAuthRepository
import com.android.systemui.keyguard.data.repository.fakeBiometricSettingsRepository
@@ -106,6 +108,7 @@ import com.android.systemui.statusbar.policy.data.repository.fakeDeviceProvision
import com.android.systemui.statusbar.sysuiStatusBarStateController
import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.mock
+import com.android.systemui.util.settings.data.repository.userAwareSecureSettingsRepository
import com.google.android.msdl.data.model.MSDLToken
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -753,7 +756,7 @@ class SceneContainerStartableTest : SysuiTestCase() {
lastSleepReason = WakeSleepReason.POWER_BUTTON,
powerButtonLaunchGestureTriggered = false,
)
- transitionStateFlow.value = Transition(from = Scenes.Shade, to = Scenes.Lockscreen)
+ transitionStateFlow.value = Transition(from = Scenes.Gone, to = Scenes.Lockscreen)
assertThat(currentSceneKey).isEqualTo(Scenes.Lockscreen)
kosmos.fakePowerRepository.updateWakefulness(
@@ -1339,7 +1342,14 @@ class SceneContainerStartableTest : SysuiTestCase() {
// Putting the device to sleep to lock it again, which shouldn't report another
// successful unlock.
kosmos.powerInteractor.setAsleepForTest()
- runCurrent()
+ advanceTimeBy(
+ kosmos.userAwareSecureSettingsRepository
+ .getInt(
+ Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
+ KeyguardViewMediator.KEYGUARD_LOCK_AFTER_DELAY_DEFAULT,
+ )
+ .toLong()
+ )
// Verify that the startable changed the scene to Lockscreen because the device locked
// following the sleep.
assertThat(currentScene).isEqualTo(Scenes.Lockscreen)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadePositionRepositoryTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadePositionRepositoryTest.kt
new file mode 100644
index 000000000000..a9a5cac6112e
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/data/repository/ShadePositionRepositoryTest.kt
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2023 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.shade.data.repository
+
+import android.view.Display
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.statusbar.commandline.commandRegistry
+import com.android.systemui.testKosmos
+import com.google.common.truth.Truth.assertThat
+import java.io.PrintWriter
+import java.io.StringWriter
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class ShadePositionRepositoryTest : SysuiTestCase() {
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
+ private val commandRegistry = kosmos.commandRegistry
+ private val pw = PrintWriter(StringWriter())
+
+ private val underTest = ShadePositionRepositoryImpl(commandRegistry)
+
+ @Before
+ fun setUp() {
+ underTest.start()
+ }
+
+ @Test
+ fun commandDisplayOverride_updatesDisplayId() =
+ testScope.runTest {
+ val displayId by collectLastValue(underTest.displayId)
+ assertThat(displayId).isEqualTo(Display.DEFAULT_DISPLAY)
+
+ val newDisplayId = 2
+ commandRegistry.onShellCommand(
+ pw,
+ arrayOf("shade_display_override", newDisplayId.toString()),
+ )
+
+ assertThat(displayId).isEqualTo(newDisplayId)
+ }
+
+ @Test
+ fun commandShadeDisplayOverride_resetsDisplayId() =
+ testScope.runTest {
+ val displayId by collectLastValue(underTest.displayId)
+ assertThat(displayId).isEqualTo(Display.DEFAULT_DISPLAY)
+
+ val newDisplayId = 2
+ commandRegistry.onShellCommand(
+ pw,
+ arrayOf("shade_display_override", newDisplayId.toString()),
+ )
+ assertThat(displayId).isEqualTo(newDisplayId)
+
+ commandRegistry.onShellCommand(pw, arrayOf("shade_display_override", "reset"))
+ assertThat(displayId).isEqualTo(Display.DEFAULT_DISPLAY)
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImplTest.kt
index 643acdbb9277..2a3878c17a1b 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImplTest.kt
@@ -16,18 +16,22 @@
package com.android.systemui.statusbar.connectivity
+import android.content.Context
+import android.os.UserHandle
import android.os.UserManager
-import androidx.test.ext.junit.runners.AndroidJUnit4
-import androidx.test.filters.SmallTest
+import android.platform.test.annotations.EnableFlags
import android.testing.TestableLooper.RunWithLooper
import androidx.lifecycle.Lifecycle
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.Flags.FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT
import com.android.systemui.SysuiTestCase
import com.android.systemui.settings.UserTracker
-import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.capture
import com.android.wifitrackerlib.WifiEntry
import com.android.wifitrackerlib.WifiPickerTracker
import com.google.common.truth.Truth.assertThat
+import java.util.concurrent.Executor
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@@ -35,36 +39,28 @@ import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers.anyList
import org.mockito.Captor
import org.mockito.Mock
-import org.mockito.Mockito.`when`
import org.mockito.Mockito.never
+import org.mockito.Mockito.times
import org.mockito.Mockito.verify
+import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
-import java.util.concurrent.Executor
+import org.mockito.kotlin.any
+import org.mockito.kotlin.mock
@SmallTest
@RunWith(AndroidJUnit4::class)
@RunWithLooper(setAsMainLooper = true)
class AccessPointControllerImplTest : SysuiTestCase() {
- @Mock
- private lateinit var userManager: UserManager
- @Mock
- private lateinit var userTracker: UserTracker
- @Mock
- private lateinit var wifiPickerTrackerFactory:
- WifiPickerTrackerFactory
- @Mock
- private lateinit var wifiPickerTracker: WifiPickerTracker
- @Mock
- private lateinit var callback: AccessPointController.AccessPointCallback
- @Mock
- private lateinit var otherCallback: AccessPointController.AccessPointCallback
- @Mock
- private lateinit var wifiEntryConnected: WifiEntry
- @Mock
- private lateinit var wifiEntryOther: WifiEntry
- @Captor
- private lateinit var wifiEntryListCaptor: ArgumentCaptor<List<WifiEntry>>
+ @Mock private lateinit var userManager: UserManager
+ @Mock private lateinit var userTracker: UserTracker
+ @Mock private lateinit var wifiPickerTrackerFactory: WifiPickerTrackerFactory
+ @Mock private lateinit var wifiPickerTracker: WifiPickerTracker
+ @Mock private lateinit var callback: AccessPointController.AccessPointCallback
+ @Mock private lateinit var otherCallback: AccessPointController.AccessPointCallback
+ @Mock private lateinit var wifiEntryConnected: WifiEntry
+ @Mock private lateinit var wifiEntryOther: WifiEntry
+ @Captor private lateinit var wifiEntryListCaptor: ArgumentCaptor<List<WifiEntry>>
private val instantExecutor = Executor { it.run() }
private lateinit var controller: AccessPointControllerImpl
@@ -72,19 +68,21 @@ class AccessPointControllerImplTest : SysuiTestCase() {
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
- `when`(wifiPickerTrackerFactory.create(any(), any(), any())).thenReturn(wifiPickerTracker)
+ `when`(wifiPickerTrackerFactory.create(any(), any(), any(), any()))
+ .thenReturn(wifiPickerTracker)
`when`(wifiPickerTracker.connectedWifiEntry).thenReturn(wifiEntryConnected)
- `when`(wifiPickerTracker.wifiEntries).thenReturn(ArrayList<WifiEntry>().apply {
- add(wifiEntryOther)
- })
+ `when`(wifiPickerTracker.wifiEntries)
+ .thenReturn(ArrayList<WifiEntry>().apply { add(wifiEntryOther) })
- controller = AccessPointControllerImpl(
+ controller =
+ AccessPointControllerImpl(
+ mContext,
userManager,
userTracker,
instantExecutor,
- wifiPickerTrackerFactory
- )
+ wifiPickerTrackerFactory,
+ )
controller.init()
}
@@ -183,13 +181,15 @@ class AccessPointControllerImplTest : SysuiTestCase() {
@Test
fun testReturnEmptyListWhenNoWifiPickerTracker() {
- `when`(wifiPickerTrackerFactory.create(any(), any(), any())).thenReturn(null)
- val otherController = AccessPointControllerImpl(
+ `when`(wifiPickerTrackerFactory.create(any(), any(), any(), any())).thenReturn(null)
+ val otherController =
+ AccessPointControllerImpl(
+ mContext,
userManager,
userTracker,
instantExecutor,
- wifiPickerTrackerFactory
- )
+ wifiPickerTrackerFactory,
+ )
otherController.init()
otherController.addAccessPointCallback(callback)
@@ -244,4 +244,19 @@ class AccessPointControllerImplTest : SysuiTestCase() {
verify(wifiEntryOther).connect(any())
verify(callback, never()).onSettingsActivityTriggered(any())
}
+
+ @Test
+ @EnableFlags(FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT)
+ fun switchUsers() {
+ val primaryUserMockContext = mock<Context>()
+ mContext.prepareCreateContextAsUser(UserHandle.of(PRIMARY_USER_ID), primaryUserMockContext)
+ controller.onUserSwitched(PRIMARY_USER_ID)
+ // Create is expected to be called once when the test starts and a second time when the user
+ // is switched.
+ verify(wifiPickerTrackerFactory, times(2)).create(any(), any(), any(), any())
+ }
+
+ private companion object {
+ private const val PRIMARY_USER_ID = 1
+ }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculatorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculatorTest.kt
index dae5542123ed..50db9f7268e4 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculatorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculatorTest.kt
@@ -21,16 +21,19 @@ import android.service.notification.StatusBarNotification
import android.view.View.VISIBLE
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
-import com.android.systemui.res.R
import com.android.systemui.SysuiTestCase
+import com.android.systemui.kosmos.testScope
import com.android.systemui.media.controls.domain.pipeline.MediaDataManager
+import com.android.systemui.res.R
import com.android.systemui.statusbar.LockscreenShadeTransitionController
import com.android.systemui.statusbar.StatusBarState
import com.android.systemui.statusbar.SysuiStatusBarStateController
import com.android.systemui.statusbar.notification.collection.NotificationEntry
+import com.android.systemui.statusbar.notification.domain.interactor.SeenNotificationsInteractor
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow
import com.android.systemui.statusbar.notification.row.ExpandableView
import com.android.systemui.statusbar.policy.ResourcesSplitShadeStateController
+import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.eq
import com.android.systemui.util.mockito.nullable
@@ -52,8 +55,11 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
private lateinit var lockscreenShadeTransitionController: LockscreenShadeTransitionController
@Mock private lateinit var mediaDataManager: MediaDataManager
@Mock private lateinit var stackLayout: NotificationStackScrollLayout
+ @Mock private lateinit var seenNotificationsInteractor: SeenNotificationsInteractor
private val testableResources = mContext.orCreateTestableResources
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
private lateinit var sizeCalculator: NotificationStackSizeCalculator
@@ -72,7 +78,9 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
lockscreenShadeTransitionController = lockscreenShadeTransitionController,
mediaDataManager = mediaDataManager,
testableResources.resources,
- ResourcesSplitShadeStateController()
+ ResourcesSplitShadeStateController(),
+ seenNotificationsInteractor = seenNotificationsInteractor,
+ scope = testScope,
)
}
@@ -85,7 +93,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
rows,
spaceForNotifications = 0f,
spaceForShelf = 0f,
- shelfHeight = 0f
+ shelfHeight = 0f,
)
assertThat(maxNotifications).isEqualTo(0)
@@ -101,7 +109,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
rows,
spaceForNotifications = Float.MAX_VALUE,
spaceForShelf = Float.MAX_VALUE,
- shelfHeight
+ shelfHeight,
)
assertThat(maxNotifications).isEqualTo(numberOfRows)
@@ -137,7 +145,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
listOf(row),
/* spaceForNotifications= */ 5f,
/* spaceForShelf= */ 0f,
- /* shelfHeight= */ 0f
+ /* shelfHeight= */ 0f,
)
assertThat(maxNotifications).isEqualTo(1)
@@ -148,11 +156,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
setGapHeight(gapHeight)
val shelfHeight = shelfHeight + dividerHeight
val spaceForNotifications =
- listOf(
- rowHeight + dividerHeight,
- gapHeight + rowHeight + dividerHeight,
- )
- .sum()
+ listOf(rowHeight + dividerHeight, gapHeight + rowHeight + dividerHeight).sum()
val spaceForShelf = gapHeight + dividerHeight + shelfHeight
val rows =
listOf(createMockRow(rowHeight), createMockRow(rowHeight), createMockRow(rowHeight))
@@ -162,7 +166,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
rows,
spaceForNotifications + 1,
spaceForShelf,
- shelfHeight
+ shelfHeight,
)
assertThat(maxNotifications).isEqualTo(2)
@@ -173,12 +177,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
// Each row in separate section.
setGapHeight(gapHeight)
- val notifSpace =
- listOf(
- rowHeight,
- dividerHeight + gapHeight + rowHeight,
- )
- .sum()
+ val notifSpace = listOf(rowHeight, dividerHeight + gapHeight + rowHeight).sum()
val shelfSpace = dividerHeight + gapHeight + shelfHeight
val spaceUsed = notifSpace + shelfSpace
@@ -209,7 +208,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
rows,
spaceForNotifications + 1,
spaceForShelf,
- shelfHeight
+ shelfHeight,
)
assertThat(maxNotifications).isEqualTo(1)
@@ -252,7 +251,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
visibleIndex = 0,
previousView = null,
stack = stackLayout,
- onLockscreen = true
+ onLockscreen = true,
)
assertThat(space.whenEnoughSpace).isEqualTo(10f)
}
@@ -272,7 +271,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
visibleIndex = 0,
previousView = null,
stack = stackLayout,
- onLockscreen = true
+ onLockscreen = true,
)
assertThat(space.whenEnoughSpace).isEqualTo(5)
}
@@ -291,7 +290,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
visibleIndex = 0,
previousView = null,
stack = stackLayout,
- onLockscreen = true
+ onLockscreen = true,
)
assertThat(space.whenSavingSpace).isEqualTo(5)
}
@@ -311,7 +310,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
visibleIndex = 0,
previousView = null,
stack = stackLayout,
- onLockscreen = true
+ onLockscreen = true,
)
assertThat(space.whenSavingSpace).isEqualTo(5)
}
@@ -330,7 +329,7 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
visibleIndex = 0,
previousView = null,
stack = stackLayout,
- onLockscreen = false
+ onLockscreen = false,
)
assertThat(space.whenEnoughSpace).isEqualTo(rowHeight)
assertThat(space.whenSavingSpace).isEqualTo(rowHeight)
@@ -340,14 +339,14 @@ class NotificationStackSizeCalculatorTest : SysuiTestCase() {
rows: List<ExpandableView>,
spaceForNotifications: Float,
spaceForShelf: Float,
- shelfHeight: Float = this.shelfHeight
+ shelfHeight: Float = this.shelfHeight,
): Int {
setupChildren(rows)
return sizeCalculator.computeMaxKeyguardNotifications(
stackLayout,
spaceForNotifications,
spaceForShelf,
- shelfHeight
+ shelfHeight,
)
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt
index a8bcfbcfc539..39a1c106cfcf 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt
@@ -16,6 +16,7 @@
package com.android.systemui.statusbar.pipeline.mobile.domain.interactor
+import android.platform.test.annotations.DisableFlags
import android.platform.test.annotations.EnableFlags
import android.telephony.CellSignalStrength
import android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN
@@ -735,9 +736,10 @@ class MobileIconInteractorTest : SysuiTestCase() {
}
@EnableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG)
+ @DisableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
@Test
// See b/346904529 for more context
- fun satBasedIcon_doesNotInflateSignalStrength() =
+ fun satBasedIcon_doesNotInflateSignalStrength_flagOff() =
testScope.runTest {
val latest by collectLastValue(underTest.signalLevelIcon)
@@ -756,7 +758,75 @@ class MobileIconInteractorTest : SysuiTestCase() {
assertThat(latest!!.level).isEqualTo(4)
}
+ @EnableFlags(
+ com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG,
+ com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN,
+ )
+ @Test
+ // See b/346904529 for more context
+ fun satBasedIcon_doesNotInflateSignalStrength_flagOn() =
+ testScope.runTest {
+ val latest by collectLastValue(underTest.signalLevelIcon)
+
+ // GIVEN a satellite connection
+ connectionRepository.isNonTerrestrial.value = true
+ // GIVEN this carrier has set INFLATE_SIGNAL_STRENGTH
+ connectionRepository.inflateSignalStrength.value = true
+
+ connectionRepository.satelliteLevel.value = 4
+ assertThat(latest!!.level).isEqualTo(4)
+
+ connectionRepository.inflateSignalStrength.value = true
+ connectionRepository.primaryLevel.value = 4
+
+ // Icon level is unaffected
+ assertThat(latest!!.level).isEqualTo(4)
+ }
+
+ @EnableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG)
+ @DisableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
+ @Test
+ fun satBasedIcon_usesPrimaryLevel_flagOff() =
+ testScope.runTest {
+ val latest by collectLastValue(underTest.signalLevelIcon)
+
+ // GIVEN a satellite connection
+ connectionRepository.isNonTerrestrial.value = true
+
+ // GIVEN primary level is set
+ connectionRepository.primaryLevel.value = 4
+ connectionRepository.satelliteLevel.value = 0
+
+ // THEN icon uses the primary level because the flag is off
+ assertThat(latest!!.level).isEqualTo(4)
+ }
+
+ @EnableFlags(
+ com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG,
+ com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN,
+ )
+ @Test
+ fun satBasedIcon_usesSatelliteLevel_flagOn() =
+ testScope.runTest {
+ val latest by collectLastValue(underTest.signalLevelIcon)
+
+ // GIVEN a satellite connection
+ connectionRepository.isNonTerrestrial.value = true
+
+ // GIVEN satellite level is set
+ connectionRepository.satelliteLevel.value = 4
+ connectionRepository.primaryLevel.value = 0
+
+ // THEN icon uses the satellite level because the flag is on
+ assertThat(latest!!.level).isEqualTo(4)
+ }
+
+ /**
+ * Context (b/377518113), this test will not be needed after FLAG_CARRIER_ROAMING_NB_IOT_NTN is
+ * rolled out. The new API should report 0 automatically if not in service.
+ */
@EnableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG)
+ @DisableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
@Test
fun satBasedIcon_reportsLevelZeroWhenOutOfService() =
testScope.runTest {
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModelTest.kt
index 4c7cdfa7fb67..038722cd9608 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconViewModelTest.kt
@@ -151,7 +151,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
iconsInteractor.isForceHidden,
repository,
context,
- MobileIconCarrierIdOverridesFake()
+ MobileIconCarrierIdOverridesFake(),
)
createAndSetViewModel()
}
@@ -359,7 +359,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
val expected =
Icon.Resource(
THREE_G.dataType,
- ContentDescription.Resource(THREE_G.dataContentDescription)
+ ContentDescription.Resource(THREE_G.dataContentDescription),
)
connectionsRepository.mobileIsDefault.value = true
repository.setNetworkTypeKey(connectionsRepository.GSM_KEY)
@@ -406,7 +406,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
val expected =
Icon.Resource(
THREE_G.dataType,
- ContentDescription.Resource(THREE_G.dataContentDescription)
+ ContentDescription.Resource(THREE_G.dataContentDescription),
)
repository.setNetworkTypeKey(connectionsRepository.GSM_KEY)
repository.setDataEnabled(true)
@@ -426,7 +426,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
val initial =
Icon.Resource(
THREE_G.dataType,
- ContentDescription.Resource(THREE_G.dataContentDescription)
+ ContentDescription.Resource(THREE_G.dataContentDescription),
)
repository.setNetworkTypeKey(connectionsRepository.GSM_KEY)
@@ -448,7 +448,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
val expected =
Icon.Resource(
THREE_G.dataType,
- ContentDescription.Resource(THREE_G.dataContentDescription)
+ ContentDescription.Resource(THREE_G.dataContentDescription),
)
repository.dataEnabled.value = true
var latest: Icon? = null
@@ -477,7 +477,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
val expected =
Icon.Resource(
THREE_G.dataType,
- ContentDescription.Resource(THREE_G.dataContentDescription)
+ ContentDescription.Resource(THREE_G.dataContentDescription),
)
assertThat(latest).isEqualTo(expected)
@@ -499,7 +499,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
val expected =
Icon.Resource(
THREE_G.dataType,
- ContentDescription.Resource(THREE_G.dataContentDescription)
+ ContentDescription.Resource(THREE_G.dataContentDescription),
)
assertThat(latest).isEqualTo(expected)
@@ -520,7 +520,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
val expected =
Icon.Resource(
THREE_G.dataType,
- ContentDescription.Resource(THREE_G.dataContentDescription)
+ ContentDescription.Resource(THREE_G.dataContentDescription),
)
assertThat(latest).isEqualTo(expected)
@@ -542,7 +542,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
val expected =
Icon.Resource(
connectionsRepository.defaultMobileIconGroup.value.dataType,
- ContentDescription.Resource(G.dataContentDescription)
+ ContentDescription.Resource(G.dataContentDescription),
)
assertThat(latest).isEqualTo(expected)
@@ -564,7 +564,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
val expected =
Icon.Resource(
THREE_G.dataType,
- ContentDescription.Resource(THREE_G.dataContentDescription)
+ ContentDescription.Resource(THREE_G.dataContentDescription),
)
assertThat(latest).isEqualTo(expected)
@@ -621,10 +621,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
underTest.activityInVisible.onEach { containerVisible = it }.launchIn(this)
repository.dataActivityDirection.value =
- DataActivityModel(
- hasActivityIn = true,
- hasActivityOut = true,
- )
+ DataActivityModel(hasActivityIn = true, hasActivityOut = true)
assertThat(inVisible).isFalse()
assertThat(outVisible).isFalse()
@@ -654,10 +651,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
underTest.activityContainerVisible.onEach { containerVisible = it }.launchIn(this)
repository.dataActivityDirection.value =
- DataActivityModel(
- hasActivityIn = true,
- hasActivityOut = false,
- )
+ DataActivityModel(hasActivityIn = true, hasActivityOut = false)
yield()
@@ -666,20 +660,14 @@ class MobileIconViewModelTest : SysuiTestCase() {
assertThat(containerVisible).isTrue()
repository.dataActivityDirection.value =
- DataActivityModel(
- hasActivityIn = false,
- hasActivityOut = true,
- )
+ DataActivityModel(hasActivityIn = false, hasActivityOut = true)
assertThat(inVisible).isFalse()
assertThat(outVisible).isTrue()
assertThat(containerVisible).isTrue()
repository.dataActivityDirection.value =
- DataActivityModel(
- hasActivityIn = false,
- hasActivityOut = false,
- )
+ DataActivityModel(hasActivityIn = false, hasActivityOut = false)
assertThat(inVisible).isFalse()
assertThat(outVisible).isFalse()
@@ -709,10 +697,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
underTest.activityContainerVisible.onEach { containerVisible = it }.launchIn(this)
repository.dataActivityDirection.value =
- DataActivityModel(
- hasActivityIn = true,
- hasActivityOut = false,
- )
+ DataActivityModel(hasActivityIn = true, hasActivityOut = false)
yield()
@@ -721,20 +706,14 @@ class MobileIconViewModelTest : SysuiTestCase() {
assertThat(containerVisible).isTrue()
repository.dataActivityDirection.value =
- DataActivityModel(
- hasActivityIn = false,
- hasActivityOut = true,
- )
+ DataActivityModel(hasActivityIn = false, hasActivityOut = true)
assertThat(inVisible).isFalse()
assertThat(outVisible).isTrue()
assertThat(containerVisible).isTrue()
repository.dataActivityDirection.value =
- DataActivityModel(
- hasActivityIn = false,
- hasActivityOut = false,
- )
+ DataActivityModel(hasActivityIn = false, hasActivityOut = false)
assertThat(inVisible).isFalse()
assertThat(outVisible).isFalse()
@@ -824,10 +803,7 @@ class MobileIconViewModelTest : SysuiTestCase() {
// sets the background on cellular
repository.hasPrioritizedNetworkCapabilities.value = true
repository.dataActivityDirection.value =
- DataActivityModel(
- hasActivityIn = true,
- hasActivityOut = true,
- )
+ DataActivityModel(hasActivityIn = true, hasActivityOut = true)
assertThat(roaming).isFalse()
assertThat(networkTypeIcon).isNull()
@@ -838,11 +814,13 @@ class MobileIconViewModelTest : SysuiTestCase() {
}
@EnableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG)
+ @DisableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
@Test
- fun nonTerrestrial_usesSatelliteIcon() =
+ fun nonTerrestrial_usesSatelliteIcon_flagOff() =
testScope.runTest {
repository.isNonTerrestrial.value = true
repository.setAllLevels(0)
+ repository.satelliteLevel.value = 0
val latest by
collectLastValue(underTest.icon.filterIsInstance(SignalIconModel.Satellite::class))
@@ -853,28 +831,66 @@ class MobileIconViewModelTest : SysuiTestCase() {
// 1-2 -> 1 bar
repository.setAllLevels(1)
+ repository.satelliteLevel.value = 1
assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_1)
repository.setAllLevels(2)
+ repository.satelliteLevel.value = 2
assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_1)
// 3-4 -> 2 bars
repository.setAllLevels(3)
+ repository.satelliteLevel.value = 3
assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_2)
repository.setAllLevels(4)
+ repository.satelliteLevel.value = 4
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_2)
+ }
+
+ @EnableFlags(
+ com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG,
+ com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN,
+ )
+ @Test
+ fun nonTerrestrial_usesSatelliteIcon_flagOn() =
+ testScope.runTest {
+ repository.isNonTerrestrial.value = true
+ repository.satelliteLevel.value = 0
+
+ val latest by
+ collectLastValue(underTest.icon.filterIsInstance(SignalIconModel.Satellite::class))
+
+ // Level 0 -> no connection
+ assertThat(latest).isNotNull()
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_0)
+
+ // 1-2 -> 1 bar
+ repository.satelliteLevel.value = 1
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_1)
+
+ repository.satelliteLevel.value = 2
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_1)
+
+ // 3-4 -> 2 bars
+ repository.satelliteLevel.value = 3
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_2)
+
+ repository.satelliteLevel.value = 4
assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_2)
}
@EnableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG)
+ @DisableFlags(com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
@Test
- fun satelliteIcon_ignoresInflateSignalStrength() =
+ fun satelliteIcon_ignoresInflateSignalStrength_flagOff() =
testScope.runTest {
// Note that this is the exact same test as above, but with inflateSignalStrength set to
// true we note that the level is unaffected by inflation
repository.inflateSignalStrength.value = true
repository.isNonTerrestrial.value = true
repository.setAllLevels(0)
+ repository.satelliteLevel.value = 0
val latest by
collectLastValue(underTest.icon.filterIsInstance(SignalIconModel.Satellite::class))
@@ -885,16 +901,55 @@ class MobileIconViewModelTest : SysuiTestCase() {
// 1-2 -> 1 bar
repository.setAllLevels(1)
+ repository.satelliteLevel.value = 1
assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_1)
repository.setAllLevels(2)
+ repository.satelliteLevel.value = 2
assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_1)
// 3-4 -> 2 bars
repository.setAllLevels(3)
+ repository.satelliteLevel.value = 3
assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_2)
repository.setAllLevels(4)
+ repository.satelliteLevel.value = 4
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_2)
+ }
+
+ @EnableFlags(
+ com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG,
+ com.android.internal.telephony.flags.Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN,
+ )
+ @Test
+ fun satelliteIcon_ignoresInflateSignalStrength_flagOn() =
+ testScope.runTest {
+ // Note that this is the exact same test as above, but with inflateSignalStrength set to
+ // true we note that the level is unaffected by inflation
+ repository.inflateSignalStrength.value = true
+ repository.isNonTerrestrial.value = true
+ repository.satelliteLevel.value = 0
+
+ val latest by
+ collectLastValue(underTest.icon.filterIsInstance(SignalIconModel.Satellite::class))
+
+ // Level 0 -> no connection
+ assertThat(latest).isNotNull()
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_0)
+
+ // 1-2 -> 1 bar
+ repository.satelliteLevel.value = 1
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_1)
+
+ repository.satelliteLevel.value = 2
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_1)
+
+ // 3-4 -> 2 bars
+ repository.satelliteLevel.value = 3
+ assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_2)
+
+ repository.satelliteLevel.value = 4
assertThat(latest!!.icon.res).isEqualTo(R.drawable.ic_satellite_connected_2)
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositorySwitcherTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositorySwitcherTest.kt
index b5dbc3fe1b4d..33223aef11ff 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositorySwitcherTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositorySwitcherTest.kt
@@ -29,6 +29,7 @@ import com.android.systemui.statusbar.pipeline.wifi.data.repository.demo.DemoMod
import com.android.systemui.statusbar.pipeline.wifi.data.repository.demo.DemoWifiRepository
import com.android.systemui.statusbar.pipeline.wifi.data.repository.demo.model.FakeWifiEventModel
import com.android.systemui.statusbar.pipeline.wifi.data.repository.prod.WifiRepositoryImpl
+import com.android.systemui.user.data.repository.FakeUserRepository
import com.android.systemui.util.concurrency.FakeExecutor
import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.kotlinArgumentCaptor
@@ -71,6 +72,7 @@ class WifiRepositorySwitcherTest : SysuiTestCase() {
private val demoModelFlow = MutableStateFlow<FakeWifiEventModel?>(null)
private val mainExecutor = FakeExecutor(FakeSystemClock())
+ private val userRepository = FakeUserRepository()
private val testDispatcher = UnconfinedTestDispatcher()
private val testScope = TestScope(testDispatcher)
@@ -82,10 +84,13 @@ class WifiRepositorySwitcherTest : SysuiTestCase() {
// Never start in demo mode
whenever(demoModeController.isInDemoMode).thenReturn(false)
- whenever(wifiPickerTrackerFactory.create(any(), any(), any())).thenReturn(wifiPickerTracker)
+ whenever(wifiPickerTrackerFactory.create(any(), any(), any(), any()))
+ .thenReturn(wifiPickerTracker)
realImpl =
WifiRepositoryImpl(
+ mContext,
+ userRepository,
testScope.backgroundScope,
mainExecutor,
testDispatcher,
@@ -97,11 +102,7 @@ class WifiRepositorySwitcherTest : SysuiTestCase() {
whenever(demoModeWifiDataSource.wifiEvents).thenReturn(demoModelFlow)
- demoImpl =
- DemoWifiRepository(
- demoModeWifiDataSource,
- testScope.backgroundScope,
- )
+ demoImpl = DemoWifiRepository(demoModeWifiDataSource, testScope.backgroundScope)
underTest =
WifiRepositorySwitcher(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/user/data/repository/UserRepositoryImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/user/data/repository/UserRepositoryImplTest.kt
index 9b47eaddffd6..8a4593032748 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/user/data/repository/UserRepositoryImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/user/data/repository/UserRepositoryImplTest.kt
@@ -30,6 +30,7 @@ import com.android.systemui.broadcast.broadcastDispatcher
import com.android.systemui.kosmos.testDispatcher
import com.android.systemui.kosmos.testScope
import com.android.systemui.kosmos.useUnconfinedTestDispatcher
+import com.android.systemui.res.R
import com.android.systemui.settings.FakeUserTracker
import com.android.systemui.testKosmos
import com.android.systemui.user.data.model.SelectedUserModel
@@ -74,6 +75,10 @@ class UserRepositoryImplTest : SysuiTestCase() {
fun setUp() {
MockitoAnnotations.initMocks(this)
tracker = FakeUserTracker()
+ context.orCreateTestableResources.addOverride(
+ R.bool.config_userSwitchingMustGoThroughLoginScreen,
+ false,
+ )
}
@Test
diff --git a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
index 24d619119983..df9f7053c3f3 100644
--- a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
+++ b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
@@ -35,6 +35,7 @@ import android.view.ViewTreeObserver.OnGlobalLayoutListener
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.broadcast.BroadcastDispatcher
import com.android.systemui.customization.R
import com.android.systemui.dagger.qualifiers.Background
@@ -62,6 +63,7 @@ import com.android.systemui.plugins.clocks.WeatherData
import com.android.systemui.plugins.clocks.ZenData
import com.android.systemui.plugins.clocks.ZenData.ZenMode
import com.android.systemui.res.R as SysuiR
+import com.android.systemui.settings.UserTracker
import com.android.systemui.shared.regionsampling.RegionSampler
import com.android.systemui.statusbar.policy.BatteryController
import com.android.systemui.statusbar.policy.BatteryController.BatteryStateChangeCallback
@@ -80,7 +82,6 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
-import com.android.app.tracing.coroutines.launchTraced as launch
/**
* Controller for a Clock provided by the registry and used on the keyguard. Instantiated by
@@ -103,6 +104,7 @@ constructor(
private val featureFlags: FeatureFlagsClassic,
private val zenModeController: ZenModeController,
private val zenModeInteractor: ZenModeInteractor,
+ private val userTracker: UserTracker,
) {
var loggers =
listOf(
@@ -120,6 +122,10 @@ constructor(
connectClock(value)
}
+ private fun is24HourFormat(userId: Int? = null): Boolean {
+ return DateFormat.is24HourFormat(context, userId ?: userTracker.userId)
+ }
+
private fun disconnectClock(clock: ClockController?) {
if (clock == null) {
return
@@ -186,7 +192,7 @@ constructor(
var pastVisibility: Int? = null
override fun onViewAttachedToWindow(view: View) {
- clock.events.onTimeFormatChanged(DateFormat.is24HourFormat(context))
+ clock.events.onTimeFormatChanged(is24HourFormat())
// Match the asing for view.parent's layout classes.
smallClockFrame =
(view.parent as ViewGroup)?.also { frame ->
@@ -218,7 +224,7 @@ constructor(
largeClockOnAttachStateChangeListener =
object : OnAttachStateChangeListener {
override fun onViewAttachedToWindow(p0: View) {
- clock.events.onTimeFormatChanged(DateFormat.is24HourFormat(context))
+ clock.events.onTimeFormatChanged(is24HourFormat())
}
override fun onViewDetachedFromWindow(p0: View) {}
@@ -358,7 +364,7 @@ constructor(
}
override fun onTimeFormatChanged(timeFormat: String?) {
- clock?.run { events.onTimeFormatChanged(DateFormat.is24HourFormat(context)) }
+ clock?.run { events.onTimeFormatChanged(is24HourFormat()) }
}
override fun onTimeZoneChanged(timeZone: TimeZone) {
@@ -366,7 +372,7 @@ constructor(
}
override fun onUserSwitchComplete(userId: Int) {
- clock?.run { events.onTimeFormatChanged(DateFormat.is24HourFormat(context)) }
+ clock?.run { events.onTimeFormatChanged(is24HourFormat(userId)) }
zenModeCallback.onNextAlarmChanged()
}
diff --git a/packages/SystemUI/src/com/android/systemui/authentication/data/repository/AuthenticationRepository.kt b/packages/SystemUI/src/com/android/systemui/authentication/data/repository/AuthenticationRepository.kt
index c9c4fd594adc..6635d8b06a5d 100644
--- a/packages/SystemUI/src/com/android/systemui/authentication/data/repository/AuthenticationRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/authentication/data/repository/AuthenticationRepository.kt
@@ -22,6 +22,7 @@ import android.annotation.UserIdInt
import android.app.admin.DevicePolicyManager
import android.content.IntentFilter
import android.os.UserHandle
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.internal.widget.LockPatternUtils
import com.android.internal.widget.LockscreenCredential
import com.android.keyguard.KeyguardSecurityModel
@@ -57,7 +58,6 @@ import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
-import com.android.app.tracing.coroutines.launchTraced as launch
import kotlinx.coroutines.withContext
/** Defines interface for classes that can access authentication-related application state. */
@@ -178,6 +178,16 @@ interface AuthenticationRepository {
* profile of an organization-owned device.
*/
@UserIdInt suspend fun getProfileWithMinFailedUnlockAttemptsForWipe(): Int
+
+ /**
+ * Returns the device policy enforced maximum time to lock the device, in milliseconds. When the
+ * device goes to sleep, this is the maximum time the device policy allows to wait before
+ * locking the device, despite what the user setting might be set to.
+ */
+ suspend fun getMaximumTimeToLock(): Long
+
+ /** Returns `true` if the power button should instantly lock the device, `false` otherwise. */
+ suspend fun getPowerButtonInstantlyLocks(): Boolean
}
@SysUISingleton
@@ -324,6 +334,19 @@ constructor(
}
}
+ override suspend fun getMaximumTimeToLock(): Long {
+ return withContext(backgroundDispatcher) {
+ devicePolicyManager.getMaximumTimeToLock(/* admin= */ null, selectedUserId)
+ }
+ }
+
+ /** Returns `true` if the power button should instantly lock the device, `false` otherwise. */
+ override suspend fun getPowerButtonInstantlyLocks(): Boolean {
+ return withContext(backgroundDispatcher) {
+ lockPatternUtils.getPowerButtonInstantlyLocks(selectedUserId)
+ }
+ }
+
private val selectedUserId: Int
@UserIdInt get() = userRepository.getSelectedUserInfo().id
diff --git a/packages/SystemUI/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractor.kt b/packages/SystemUI/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractor.kt
index 67579fd7f696..1c994731c393 100644
--- a/packages/SystemUI/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/authentication/domain/interactor/AuthenticationInteractor.kt
@@ -17,6 +17,7 @@
package com.android.systemui.authentication.domain.interactor
import android.os.UserHandle
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.internal.widget.LockPatternUtils
import com.android.internal.widget.LockPatternView
import com.android.internal.widget.LockscreenCredential
@@ -49,7 +50,6 @@ import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
-import com.android.app.tracing.coroutines.launchTraced as launch
/**
* Hosts application business logic related to user authentication.
@@ -215,7 +215,7 @@ constructor(
*/
suspend fun authenticate(
input: List<Any>,
- tryAutoConfirm: Boolean = false
+ tryAutoConfirm: Boolean = false,
): AuthenticationResult {
if (input.isEmpty()) {
throw IllegalArgumentException("Input was empty!")
@@ -254,6 +254,20 @@ constructor(
return AuthenticationResult.FAILED
}
+ /**
+ * Returns the device policy enforced maximum time to lock the device, in milliseconds. When the
+ * device goes to sleep, this is the maximum time the device policy allows to wait before
+ * locking the device, despite what the user setting might be set to.
+ */
+ suspend fun getMaximumTimeToLock(): Long {
+ return repository.getMaximumTimeToLock()
+ }
+
+ /** Returns `true` if the power button should instantly lock the device, `false` otherwise. */
+ suspend fun getPowerButtonInstantlyLocks(): Boolean {
+ return !getAuthenticationMethod().isSecure || repository.getPowerButtonInstantlyLocks()
+ }
+
private suspend fun shouldSkipAuthenticationAttempt(
authenticationMethod: AuthenticationMethodModel,
isAutoConfirmAttempt: Boolean,
diff --git a/packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt b/packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt
index f8254592819b..a107322423bb 100644
--- a/packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt
+++ b/packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt
@@ -36,6 +36,7 @@ import com.android.systemui.controls.controller.AuxiliaryPersistenceWrapper
import com.android.systemui.controls.controller.ControlsFavoritePersistenceWrapper
import com.android.systemui.keyguard.domain.backup.KeyguardQuickAffordanceBackupHelper
import com.android.systemui.people.widget.PeopleBackupHelper
+import com.android.systemui.qs.panels.domain.backup.QSPreferencesBackupHelper
import com.android.systemui.res.R
import com.android.systemui.settings.UserFileManagerImpl
@@ -58,9 +59,9 @@ open class BackupHelper : BackupAgentHelper() {
private const val PEOPLE_TILES_BACKUP_KEY = "systemui.people.shared_preferences"
private const val KEYGUARD_QUICK_AFFORDANCES_BACKUP_KEY =
"systemui.keyguard.quickaffordance.shared_preferences"
- private const val COMMUNAL_PREFS_BACKUP_KEY =
- "systemui.communal.shared_preferences"
+ private const val COMMUNAL_PREFS_BACKUP_KEY = "systemui.communal.shared_preferences"
private const val COMMUNAL_STATE_BACKUP_KEY = "systemui.communal_state"
+ private const val QS_PREFERENCES_BACKUP_KEY = "systemui.qs.shared_preferences"
val controlsDataLock = Any()
const val ACTION_RESTORE_FINISHED = "com.android.systemui.backup.RESTORE_FINISHED"
const val PERMISSION_SELF = "com.android.systemui.permission.SELF"
@@ -74,22 +75,20 @@ open class BackupHelper : BackupAgentHelper() {
val keys = PeopleBackupHelper.getFilesToBackup()
addHelper(
PEOPLE_TILES_BACKUP_KEY,
- PeopleBackupHelper(this, userHandle, keys.toTypedArray())
+ PeopleBackupHelper(this, userHandle, keys.toTypedArray()),
)
addHelper(
KEYGUARD_QUICK_AFFORDANCES_BACKUP_KEY,
- KeyguardQuickAffordanceBackupHelper(
- context = this,
- userId = userHandle.identifier,
- ),
+ KeyguardQuickAffordanceBackupHelper(context = this, userId = userHandle.identifier),
+ )
+ addHelper(
+ QS_PREFERENCES_BACKUP_KEY,
+ QSPreferencesBackupHelper(context = this, userId = userHandle.identifier),
)
if (communalEnabled()) {
addHelper(
COMMUNAL_PREFS_BACKUP_KEY,
- CommunalPrefsBackupHelper(
- context = this,
- userId = userHandle.identifier,
- )
+ CommunalPrefsBackupHelper(context = this, userId = userHandle.identifier),
)
addHelper(
COMMUNAL_STATE_BACKUP_KEY,
@@ -110,10 +109,7 @@ open class BackupHelper : BackupAgentHelper() {
}
private fun addControlsHelper(userId: Int) {
- val file = UserFileManagerImpl.createFile(
- userId = userId,
- fileName = CONTROLS,
- )
+ val file = UserFileManagerImpl.createFile(userId = userId, fileName = CONTROLS)
// The map in mapOf is guaranteed to be order preserving
val controlsMap = mapOf(file.getPath() to getPPControlsFile(this, userId))
NoOverwriteFileBackupHelper(controlsDataLock, this, controlsMap).also {
@@ -134,6 +130,7 @@ open class BackupHelper : BackupAgentHelper() {
* @property lock a lock to hold while backing up and restoring the files.
* @property context the context of the [BackupAgent]
* @property fileNamesAndPostProcess a map from the filenames to back up and the post processing
+ *
* ```
* actions to take
* ```
@@ -141,7 +138,7 @@ open class BackupHelper : BackupAgentHelper() {
private class NoOverwriteFileBackupHelper(
val lock: Any,
val context: Context,
- val fileNamesAndPostProcess: Map<String, () -> Unit>
+ val fileNamesAndPostProcess: Map<String, () -> Unit>,
) : FileBackupHelper(context, *fileNamesAndPostProcess.keys.toTypedArray()) {
override fun restoreEntity(data: BackupDataInputStream) {
@@ -152,11 +149,12 @@ open class BackupHelper : BackupAgentHelper() {
return
}
synchronized(lock) {
- traceSection("File restore: ${data.key}") {
- super.restoreEntity(data)
- }
- Log.d(TAG, "Finishing restore for ${data.key} for user ${context.userId}. " +
- "Starting postProcess.")
+ traceSection("File restore: ${data.key}") { super.restoreEntity(data) }
+ Log.d(
+ TAG,
+ "Finishing restore for ${data.key} for user ${context.userId}. " +
+ "Starting postProcess.",
+ )
traceSection("Postprocess: ${data.key}") {
fileNamesAndPostProcess.get(data.key)?.invoke()
}
@@ -167,7 +165,7 @@ open class BackupHelper : BackupAgentHelper() {
override fun performBackup(
oldState: ParcelFileDescriptor?,
data: BackupDataOutput?,
- newState: ParcelFileDescriptor?
+ newState: ParcelFileDescriptor?,
) {
synchronized(lock) { super.performBackup(oldState, data, newState) }
}
@@ -176,15 +174,13 @@ open class BackupHelper : BackupAgentHelper() {
private fun getPPControlsFile(context: Context, userId: Int): () -> Unit {
return {
- val file = UserFileManagerImpl.createFile(
- userId = userId,
- fileName = BackupHelper.CONTROLS,
- )
+ val file = UserFileManagerImpl.createFile(userId = userId, fileName = BackupHelper.CONTROLS)
if (file.exists()) {
- val dest = UserFileManagerImpl.createFile(
- userId = userId,
- fileName = AuxiliaryPersistenceWrapper.AUXILIARY_FILE_NAME,
- )
+ val dest =
+ UserFileManagerImpl.createFile(
+ userId = userId,
+ fileName = AuxiliaryPersistenceWrapper.AUXILIARY_FILE_NAME,
+ )
file.copyTo(dest)
val jobScheduler = context.getSystemService(JobScheduler::class.java)
jobScheduler?.schedule(
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/DeviceEntryModule.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/DeviceEntryModule.kt
index c464a66ea0c3..6c335e71cfde 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/DeviceEntryModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/DeviceEntryModule.kt
@@ -18,13 +18,18 @@ package com.android.systemui.deviceentry
import com.android.keyguard.EmptyLockIconViewController
import com.android.keyguard.LockIconViewController
+import com.android.systemui.CoreStartable
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.deviceentry.data.repository.DeviceEntryRepositoryModule
import com.android.systemui.deviceentry.data.repository.FaceWakeUpTriggersConfigModule
+import com.android.systemui.deviceentry.domain.interactor.DeviceUnlockedInteractor
import com.android.systemui.keyguard.ui.transitions.DeviceEntryIconTransition
+import dagger.Binds
import dagger.Lazy
import dagger.Module
import dagger.Provides
+import dagger.multibindings.ClassKey
+import dagger.multibindings.IntoMap
import dagger.multibindings.Multibinds
@Module(includes = [DeviceEntryRepositoryModule::class, FaceWakeUpTriggersConfigModule::class])
@@ -34,6 +39,13 @@ abstract class DeviceEntryModule {
*/
@Multibinds abstract fun deviceEntryIconTransitionSet(): Set<DeviceEntryIconTransition>
+ @Binds
+ @IntoMap
+ @ClassKey(DeviceUnlockedInteractor.Activator::class)
+ abstract fun deviceUnlockedInteractorActivator(
+ activator: DeviceUnlockedInteractor.Activator
+ ): CoreStartable
+
companion object {
@Provides
@SysUISingleton
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/data/repository/DeviceEntryRepository.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/data/repository/DeviceEntryRepository.kt
index 3f937bba46d4..675f00a89d23 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/data/repository/DeviceEntryRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/data/repository/DeviceEntryRepository.kt
@@ -5,6 +5,7 @@ import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCall
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Application
import com.android.systemui.dagger.qualifiers.Background
+import com.android.systemui.deviceentry.shared.model.DeviceUnlockStatus
import com.android.systemui.statusbar.phone.KeyguardBypassController
import com.android.systemui.user.data.repository.UserRepository
import dagger.Binds
@@ -42,6 +43,8 @@ interface DeviceEntryRepository {
*/
val isBypassEnabled: StateFlow<Boolean>
+ val deviceUnlockStatus: MutableStateFlow<DeviceUnlockStatus>
+
/**
* Whether the lockscreen is enabled for the current user. This is `true` whenever the user has
* chosen any secure authentication method and even if they set the lockscreen to be dismissed
@@ -84,6 +87,9 @@ constructor(
initialValue = keyguardBypassController.bypassEnabled,
)
+ override val deviceUnlockStatus =
+ MutableStateFlow(DeviceUnlockStatus(isUnlocked = false, deviceUnlockSource = null))
+
override suspend fun isLockscreenEnabled(): Boolean {
return withContext(backgroundDispatcher) {
val selectedUserId = userRepository.getSelectedUserInfo().id
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractor.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractor.kt
index 5259c5dca39f..67584a599e5c 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractor.kt
@@ -16,7 +16,10 @@
package com.android.systemui.deviceentry.domain.interactor
+import android.provider.Settings
+import android.util.Log
import androidx.annotation.VisibleForTesting
+import com.android.systemui.CoreStartable
import com.android.systemui.authentication.domain.interactor.AuthenticationInteractor
import com.android.systemui.authentication.shared.model.AuthenticationMethodModel
import com.android.systemui.dagger.SysUISingleton
@@ -26,42 +29,47 @@ import com.android.systemui.deviceentry.shared.model.DeviceEntryRestrictionReaso
import com.android.systemui.deviceentry.shared.model.DeviceUnlockSource
import com.android.systemui.deviceentry.shared.model.DeviceUnlockStatus
import com.android.systemui.flags.SystemPropertiesHelper
-import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionInteractor
+import com.android.systemui.keyguard.KeyguardViewMediator
import com.android.systemui.keyguard.domain.interactor.TrustInteractor
-import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.lifecycle.ExclusiveActivatable
import com.android.systemui.power.domain.interactor.PowerInteractor
-import com.android.systemui.utils.coroutines.flow.flatMapLatestConflated
+import com.android.systemui.power.shared.model.WakeSleepReason
+import com.android.systemui.util.settings.repository.UserAwareSecureSettingsRepository
import javax.inject.Inject
+import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapLatest
-import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
-import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.launch
@OptIn(ExperimentalCoroutinesApi::class)
@SysUISingleton
class DeviceUnlockedInteractor
@Inject
constructor(
- @Application private val applicationScope: CoroutineScope,
- authenticationInteractor: AuthenticationInteractor,
- deviceEntryRepository: DeviceEntryRepository,
+ private val authenticationInteractor: AuthenticationInteractor,
+ private val repository: DeviceEntryRepository,
trustInteractor: TrustInteractor,
faceAuthInteractor: DeviceEntryFaceAuthInteractor,
fingerprintAuthInteractor: DeviceEntryFingerprintAuthInteractor,
private val powerInteractor: PowerInteractor,
private val biometricSettingsInteractor: DeviceEntryBiometricSettingsInteractor,
private val systemPropertiesHelper: SystemPropertiesHelper,
- keyguardTransitionInteractor: KeyguardTransitionInteractor,
-) {
+ private val userAwareSecureSettingsRepository: UserAwareSecureSettingsRepository,
+) : ExclusiveActivatable() {
private val deviceUnlockSource =
merge(
@@ -69,7 +77,7 @@ constructor(
faceAuthInteractor.isAuthenticated
.filter { it }
.map {
- if (deviceEntryRepository.isBypassEnabled.value) {
+ if (repository.isBypassEnabled.value) {
DeviceUnlockSource.FaceWithBypass
} else {
DeviceUnlockSource.FaceWithoutBypass
@@ -163,43 +171,145 @@ constructor(
* proceed.
*/
val deviceUnlockStatus: StateFlow<DeviceUnlockStatus> =
- authenticationInteractor.authenticationMethod
- .flatMapLatest { authMethod ->
- if (!authMethod.isSecure) {
- flowOf(DeviceUnlockStatus(true, null))
- } else if (authMethod == AuthenticationMethodModel.Sim) {
- // Device is locked if SIM is locked.
- flowOf(DeviceUnlockStatus(false, null))
- } else {
- combine(
- powerInteractor.isAsleep,
- isInLockdown,
- keyguardTransitionInteractor
- .transitionValue(KeyguardState.AOD)
- .map { it == 1f }
- .distinctUntilChanged(),
- ::Triple,
- )
- .flatMapLatestConflated { (isAsleep, isInLockdown, isAod) ->
- val isForceLocked =
- when {
- isAsleep && !isAod -> true
- isInLockdown -> true
- else -> false
- }
- if (isForceLocked) {
- flowOf(DeviceUnlockStatus(false, null))
+ repository.deviceUnlockStatus.asStateFlow()
+
+ override suspend fun onActivated(): Nothing {
+ authenticationInteractor.authenticationMethod.collectLatest { authMethod ->
+ if (!authMethod.isSecure) {
+ // Device remains unlocked as long as the authentication method is not secure.
+ Log.d(TAG, "remaining unlocked because auth method not secure")
+ repository.deviceUnlockStatus.value = DeviceUnlockStatus(true, null)
+ } else if (authMethod == AuthenticationMethodModel.Sim) {
+ // Device remains locked while SIM is locked.
+ Log.d(TAG, "remaining locked because SIM locked")
+ repository.deviceUnlockStatus.value = DeviceUnlockStatus(false, null)
+ } else {
+ handleLockAndUnlockEvents()
+ }
+ }
+
+ awaitCancellation()
+ }
+
+ private suspend fun handleLockAndUnlockEvents() {
+ try {
+ Log.d(TAG, "started watching for lock and unlock events")
+ coroutineScope {
+ launch { handleUnlockEvents() }
+ launch { handleLockEvents() }
+ }
+ } finally {
+ Log.d(TAG, "stopped watching for lock and unlock events")
+ }
+ }
+
+ private suspend fun handleUnlockEvents() {
+ // Unlock the device when a new unlock source is detected.
+ deviceUnlockSource.collect {
+ Log.d(TAG, "unlocking due to \"$it\"")
+ repository.deviceUnlockStatus.value = DeviceUnlockStatus(true, it)
+ }
+ }
+
+ private suspend fun handleLockEvents() {
+ merge(
+ // Device wakefulness events.
+ powerInteractor.detailedWakefulness
+ .map { Pair(it.isAsleep(), it.lastSleepReason) }
+ .distinctUntilChangedBy { it.first }
+ .map { (isAsleep, lastSleepReason) ->
+ if (isAsleep) {
+ if (
+ lastSleepReason == WakeSleepReason.POWER_BUTTON &&
+ authenticationInteractor.getPowerButtonInstantlyLocks()
+ ) {
+ LockImmediately("locked instantly from power button")
} else {
- deviceUnlockSource.map { DeviceUnlockStatus(true, it) }
+ LockWithDelay("entering sleep")
}
+ } else {
+ CancelDelayedLock("waking up")
}
+ },
+ // Device enters lockdown.
+ isInLockdown
+ .distinctUntilChanged()
+ .filter { it }
+ .map { LockImmediately("lockdown") },
+ )
+ .collectLatest(::onLockEvent)
+ }
+
+ private suspend fun onLockEvent(event: LockEvent) {
+ val debugReason = event.debugReason
+ when (event) {
+ is LockImmediately -> {
+ Log.d(TAG, "locking without delay due to \"$debugReason\"")
+ repository.deviceUnlockStatus.value = DeviceUnlockStatus(false, null)
+ }
+
+ is LockWithDelay -> {
+ val lockDelay = lockDelay()
+ Log.d(TAG, "locking in ${lockDelay}ms due to \"$debugReason\"")
+ try {
+ delay(lockDelay)
+ Log.d(
+ TAG,
+ "locking after having waited for ${lockDelay}ms due to \"$debugReason\"",
+ )
+ repository.deviceUnlockStatus.value = DeviceUnlockStatus(false, null)
+ } catch (_: CancellationException) {
+ Log.d(
+ TAG,
+ "delayed locking canceled, original delay was ${lockDelay}ms and reason was \"$debugReason\"",
+ )
}
}
- .stateIn(
- scope = applicationScope,
- started = SharingStarted.Eagerly,
- initialValue = DeviceUnlockStatus(false, null),
- )
+
+ is CancelDelayedLock -> {
+ // Do nothing, the mere receipt of this inside of a "latest" block means that any
+ // previous coroutine is automatically canceled.
+ }
+ }
+ }
+
+ /**
+ * Returns the amount of time to wait before locking down the device after the device has been
+ * put to sleep by the user, in milliseconds.
+ */
+ private suspend fun lockDelay(): Long {
+ val lockAfterScreenTimeoutSetting =
+ userAwareSecureSettingsRepository
+ .getInt(
+ Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
+ KeyguardViewMediator.KEYGUARD_LOCK_AFTER_DELAY_DEFAULT,
+ )
+ .toLong()
+ Log.d(TAG, "Lock after screen timeout setting set to ${lockAfterScreenTimeoutSetting}ms")
+
+ val maxTimeToLockDevicePolicy = authenticationInteractor.getMaximumTimeToLock()
+ Log.d(TAG, "Device policy max set to ${maxTimeToLockDevicePolicy}ms")
+
+ if (maxTimeToLockDevicePolicy <= 0) {
+ // No device policy enforced maximum.
+ Log.d(TAG, "No device policy max, delay is ${lockAfterScreenTimeoutSetting}ms")
+ return lockAfterScreenTimeoutSetting
+ }
+
+ val screenOffTimeoutSetting =
+ userAwareSecureSettingsRepository
+ .getInt(
+ Settings.System.SCREEN_OFF_TIMEOUT,
+ KeyguardViewMediator.KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT,
+ )
+ .coerceAtLeast(0)
+ .toLong()
+ Log.d(TAG, "Screen off timeout setting set to ${screenOffTimeoutSetting}ms")
+
+ return (maxTimeToLockDevicePolicy - screenOffTimeoutSetting)
+ .coerceIn(minimumValue = 0, maximumValue = lockAfterScreenTimeoutSetting)
+ .also { Log.d(TAG, "Device policy max enforced, delay is ${it}ms") }
+ }
private fun DeviceEntryRestrictionReason?.isInLockdown(): Boolean {
return when (this) {
@@ -226,7 +336,30 @@ constructor(
return systemPropertiesHelper.get(SYS_BOOT_REASON_PROP) == REBOOT_MAINLINE_UPDATE
}
+ /** [CoreStartable] that activates the [DeviceUnlockedInteractor]. */
+ class Activator
+ @Inject
+ constructor(
+ @Application private val applicationScope: CoroutineScope,
+ private val interactor: DeviceUnlockedInteractor,
+ ) : CoreStartable {
+ override fun start() {
+ applicationScope.launch { interactor.activate() }
+ }
+ }
+
+ private sealed interface LockEvent {
+ val debugReason: String
+ }
+
+ private data class LockImmediately(override val debugReason: String) : LockEvent
+
+ private data class LockWithDelay(override val debugReason: String) : LockEvent
+
+ private data class CancelDelayedLock(override val debugReason: String) : LockEvent
+
companion object {
+ private val TAG = "DeviceUnlockedInteractor"
@VisibleForTesting const val SYS_BOOT_REASON_PROP = "sys.boot.reason.last"
@VisibleForTesting const val REBOOT_MAINLINE_UPDATE = "reboot,mainline_update"
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 60a306b3e245..2ee9ddb0e453 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -239,7 +239,7 @@ public class KeyguardViewMediator implements CoreStartable, Dumpable,
private static final boolean ENABLE_NEW_KEYGUARD_SHELL_TRANSITIONS =
Flags.ensureKeyguardDoesTransitionStarting();
- private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
+ public static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
private static final long KEYGUARD_DONE_PENDING_TIMEOUT_MS = 3000;
private static final boolean DEBUG = KeyguardConstants.DEBUG;
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/transitions/ClockSizeTransition.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/transitions/ClockSizeTransition.kt
index c11005d38986..a595d815e016 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/transitions/ClockSizeTransition.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/view/layout/sections/transitions/ClockSizeTransition.kt
@@ -93,18 +93,18 @@ class ClockSizeTransition(
fromBounds: Rect,
toBounds: Rect,
fromSSBounds: Rect?,
- toSSBounds: Rect?
+ toSSBounds: Rect?,
) {}
override fun createAnimator(
sceenRoot: ViewGroup,
startValues: TransitionValues?,
- endValues: TransitionValues?
+ endValues: TransitionValues?,
): Animator? {
if (startValues == null || endValues == null) {
Log.w(
TAG,
- "Couldn't create animator: startValues=$startValues; endValues=$endValues"
+ "Couldn't create animator: startValues=$startValues; endValues=$endValues",
)
return null
}
@@ -137,7 +137,7 @@ class ClockSizeTransition(
"Skipping no-op transition: $toView; " +
"vis: $fromVis -> $toVis; " +
"alpha: $fromAlpha -> $toAlpha; " +
- "bounds: $fromBounds -> $toBounds; "
+ "bounds: $fromBounds -> $toBounds; ",
)
}
return null
@@ -151,7 +151,7 @@ class ClockSizeTransition(
lerp(fromBounds.left, toBounds.left, fract),
lerp(fromBounds.top, toBounds.top, fract),
lerp(fromBounds.right, toBounds.right, fract),
- lerp(fromBounds.bottom, toBounds.bottom, fract)
+ lerp(fromBounds.bottom, toBounds.bottom, fract),
)
fun assignAnimValues(src: String, fract: Float, vis: Int? = null) {
@@ -160,7 +160,7 @@ class ClockSizeTransition(
if (DEBUG) {
Log.i(
TAG,
- "$src: $toView; fract=$fract; alpha=$alpha; vis=$vis; bounds=$bounds;"
+ "$src: $toView; fract=$fract; alpha=$alpha; vis=$vis; bounds=$bounds;",
)
}
toView.setVisibility(vis ?: View.VISIBLE)
@@ -174,7 +174,7 @@ class ClockSizeTransition(
"transitioning: $toView; " +
"vis: $fromVis -> $toVis; " +
"alpha: $fromAlpha -> $toAlpha; " +
- "bounds: $fromBounds -> $toBounds; "
+ "bounds: $fromBounds -> $toBounds; ",
)
}
@@ -258,7 +258,7 @@ class ClockSizeTransition(
fromBounds: Rect,
toBounds: Rect,
fromSSBounds: Rect?,
- toSSBounds: Rect?
+ toSSBounds: Rect?,
) {
// Move normally if clock is not changing visibility
if (fromIsVis == toIsVis) return
@@ -347,12 +347,17 @@ class ClockSizeTransition(
fromBounds: Rect,
toBounds: Rect,
fromSSBounds: Rect?,
- toSSBounds: Rect?
+ toSSBounds: Rect?,
) {
// If view is changing visibility, hold it in place
if (fromIsVis == toIsVis) return
if (DEBUG) Log.i(TAG, "Holding position of ${view.id}")
- toBounds.set(fromBounds)
+
+ if (fromIsVis) {
+ toBounds.set(fromBounds)
+ } else {
+ fromBounds.set(toBounds)
+ }
}
companion object {
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactory.kt b/packages/SystemUI/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactory.kt
index d38e507082b9..913aa6f9d547 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactory.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactory.kt
@@ -42,7 +42,7 @@ import com.android.systemui.media.controls.shared.model.MediaButton
import com.android.systemui.media.controls.util.MediaControllerFactory
import com.android.systemui.media.controls.util.SessionTokenFactory
import com.android.systemui.res.R
-import com.android.systemui.util.Assert
+import com.android.systemui.util.concurrency.Execution
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@@ -63,6 +63,7 @@ constructor(
@Background private val looper: Looper,
@Background private val handler: Handler,
@Background private val bgScope: CoroutineScope,
+ private val execution: Execution,
) {
/**
@@ -108,7 +109,7 @@ constructor(
m3controller: Media3Controller,
token: SessionToken,
): MediaButton? {
- Assert.isNotMainThread()
+ require(!execution.isMainThread())
// First, get standard actions
val playOrPause =
diff --git a/packages/SystemUI/src/com/android/systemui/power/domain/interactor/PowerInteractor.kt b/packages/SystemUI/src/com/android/systemui/power/domain/interactor/PowerInteractor.kt
index 8d48c1d1d23f..1cf4c23415da 100644
--- a/packages/SystemUI/src/com/android/systemui/power/domain/interactor/PowerInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/power/domain/interactor/PowerInteractor.kt
@@ -26,11 +26,13 @@ import com.android.systemui.plugins.statusbar.StatusBarStateController
import com.android.systemui.power.data.repository.PowerRepository
import com.android.systemui.power.shared.model.ScreenPowerState
import com.android.systemui.power.shared.model.WakeSleepReason
+import com.android.systemui.power.shared.model.WakefulnessModel
import com.android.systemui.power.shared.model.WakefulnessState
import com.android.systemui.statusbar.phone.ScreenOffAnimationController
import javax.inject.Inject
import javax.inject.Provider
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
@@ -56,7 +58,7 @@ constructor(
* Unless you need to respond differently to different [WakeSleepReason]s, you should use
* [isAwake].
*/
- val detailedWakefulness = repository.wakefulness
+ val detailedWakefulness: StateFlow<WakefulnessModel> = repository.wakefulness
/**
* Whether we're awake (screen is on and responding to user touch) or asleep (screen is off, or
@@ -189,9 +191,7 @@ constructor(
* In tests, you should be able to use [setAsleepForTest] rather than calling this method
* directly.
*/
- fun onFinishedGoingToSleep(
- powerButtonLaunchGestureTriggeredDuringSleep: Boolean,
- ) {
+ fun onFinishedGoingToSleep(powerButtonLaunchGestureTriggeredDuringSleep: Boolean) {
// If the launch gesture was previously detected via onCameraLaunchGestureDetected, carry
// that state forward. It will be reset by the next onStartedGoingToSleep.
val powerButtonLaunchGestureTriggered =
@@ -255,7 +255,7 @@ constructor(
@JvmOverloads
fun PowerInteractor.setAwakeForTest(
@PowerManager.WakeReason reason: Int = PowerManager.WAKE_REASON_UNKNOWN,
- forceEmit: Boolean = false
+ forceEmit: Boolean = false,
) {
emitDuplicateWakefulnessValue = forceEmit
@@ -286,9 +286,7 @@ constructor(
emitDuplicateWakefulnessValue = forceEmit
this.onStartedGoingToSleep(reason = sleepReason)
- this.onFinishedGoingToSleep(
- powerButtonLaunchGestureTriggeredDuringSleep = false,
- )
+ this.onFinishedGoingToSleep(powerButtonLaunchGestureTriggeredDuringSleep = false)
}
/** Helper method for tests to simulate the device screen state change event. */
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepository.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepository.kt
index 971598dea0bd..b0c607303297 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepository.kt
@@ -17,9 +17,16 @@
package com.android.systemui.qs.panels.data.repository
import android.content.Context
+import android.content.IntentFilter
import android.content.SharedPreferences
+import com.android.systemui.backup.BackupHelper
+import com.android.systemui.backup.BackupHelper.Companion.ACTION_RESTORE_FINISHED
+import com.android.systemui.broadcast.BroadcastDispatcher
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Background
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.core.Logger
+import com.android.systemui.qs.panels.shared.model.PanelsLog
import com.android.systemui.qs.pipeline.shared.TileSpec
import com.android.systemui.settings.UserFileManager
import com.android.systemui.user.data.repository.UserRepository
@@ -29,9 +36,11 @@ import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onEach
/** Repository for QS user preferences. */
@OptIn(ExperimentalCoroutinesApi::class)
@@ -43,26 +52,31 @@ constructor(
private val userRepository: UserRepository,
private val defaultLargeTilesRepository: DefaultLargeTilesRepository,
@Background private val backgroundDispatcher: CoroutineDispatcher,
+ @PanelsLog private val logBuffer: LogBuffer,
+ broadcastDispatcher: BroadcastDispatcher,
) {
- /** Whether to show the labels on icon tiles for the current user. */
- val showLabels: Flow<Boolean> =
- userRepository.selectedUserInfo
- .flatMapLatest { userInfo ->
- val prefs = getSharedPrefs(userInfo.id)
- prefs.observe().emitOnStart().map { prefs.getBoolean(ICON_LABELS_KEY, false) }
- }
- .flowOn(backgroundDispatcher)
+ private val logger by lazy { Logger(logBuffer, TAG) }
+
+ private val backupRestorationEvents: Flow<Unit> =
+ broadcastDispatcher
+ .broadcastFlow(
+ filter = IntentFilter(ACTION_RESTORE_FINISHED),
+ flags = Context.RECEIVER_NOT_EXPORTED,
+ permission = BackupHelper.PERMISSION_SELF,
+ )
+ .onEach { logger.i("Restored state for QS preferences.") }
+ .emitOnStart()
/** Set of [TileSpec] to display as large tiles for the current user. */
val largeTilesSpecs: Flow<Set<TileSpec>> =
- userRepository.selectedUserInfo
- .flatMapLatest { userInfo ->
+ combine(backupRestorationEvents, userRepository.selectedUserInfo, ::Pair)
+ .flatMapLatest { (_, userInfo) ->
val prefs = getSharedPrefs(userInfo.id)
prefs.observe().emitOnStart().map {
prefs
.getStringSet(
LARGE_TILES_SPECS_KEY,
- defaultLargeTilesRepository.defaultLargeTiles.map { it.spec }.toSet()
+ defaultLargeTilesRepository.defaultLargeTiles.map { it.spec }.toSet(),
)
?.map { TileSpec.create(it) }
?.toSet() ?: defaultLargeTilesRepository.defaultLargeTiles
@@ -70,13 +84,6 @@ constructor(
}
.flowOn(backgroundDispatcher)
- /** Sets for the current user whether to show the labels on icon tiles. */
- fun setShowLabels(showLabels: Boolean) {
- with(getSharedPrefs(userRepository.getSelectedUserInfo().id)) {
- edit().putBoolean(ICON_LABELS_KEY, showLabels).apply()
- }
- }
-
/** Sets for the current user the set of [TileSpec] to display as large tiles. */
fun setLargeTilesSpecs(specs: Set<TileSpec>) {
with(getSharedPrefs(userRepository.getSelectedUserInfo().id)) {
@@ -85,15 +92,11 @@ constructor(
}
private fun getSharedPrefs(userId: Int): SharedPreferences {
- return userFileManager.getSharedPreferences(
- FILE_NAME,
- Context.MODE_PRIVATE,
- userId,
- )
+ return userFileManager.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE, userId)
}
companion object {
- private const val ICON_LABELS_KEY = "show_icon_labels"
+ private const val TAG = "QSPreferencesRepository"
private const val LARGE_TILES_SPECS_KEY = "large_tiles_specs"
const val FILE_NAME = "quick_settings_prefs"
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/domain/backup/QSPreferencesBackupHelper.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/domain/backup/QSPreferencesBackupHelper.kt
new file mode 100644
index 000000000000..2c51ca9c253f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/domain/backup/QSPreferencesBackupHelper.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2024 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.panels.domain.backup
+
+import android.app.backup.SharedPreferencesBackupHelper
+import android.content.Context
+import com.android.systemui.qs.panels.data.repository.QSPreferencesRepository.Companion.FILE_NAME
+import com.android.systemui.settings.UserFileManagerImpl
+
+class QSPreferencesBackupHelper(context: Context, userId: Int) :
+ SharedPreferencesBackupHelper(
+ context,
+ UserFileManagerImpl.createFile(userId = userId, fileName = FILE_NAME).path,
+ )
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/QuickAccessWalletTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/QuickAccessWalletTile.java
index f218d86a5aa1..37d24debe958 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/QuickAccessWalletTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/QuickAccessWalletTile.java
@@ -243,15 +243,15 @@ public class QuickAccessWalletTile extends QSTileImpl<QSTile.State> {
}
mSelectedCard = cards.get(selectedIndex);
switch (mSelectedCard.getCardImage().getType()) {
+ case TYPE_BITMAP:
+ case TYPE_ADAPTIVE_BITMAP:
+ mCardViewDrawable = mSelectedCard.getCardImage().loadDrawable(mContext);
+ break;
case TYPE_URI:
case TYPE_URI_ADAPTIVE_BITMAP:
- mCardViewDrawable = null;
- break;
case TYPE_RESOURCE:
- case TYPE_BITMAP:
- case TYPE_ADAPTIVE_BITMAP:
case TYPE_DATA:
- mCardViewDrawable = mSelectedCard.getCardImage().loadDrawable(mContext);
+ mCardViewDrawable = null;
break;
default:
Log.e(TAG, "Unknown icon type: " + mSelectedCard.getCardImage().getType());
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt
index 42d4effbac3a..63510b873951 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt
@@ -20,6 +20,7 @@ import android.content.Context
import android.content.res.Resources
import android.view.LayoutInflater
import android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
+import com.android.systemui.CoreStartable
import com.android.systemui.common.ui.ConfigurationState
import com.android.systemui.common.ui.ConfigurationStateImpl
import com.android.systemui.common.ui.GlobalConfig
@@ -29,12 +30,16 @@ import com.android.systemui.common.ui.domain.interactor.ConfigurationInteractor
import com.android.systemui.common.ui.domain.interactor.ConfigurationInteractorImpl
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.res.R
+import com.android.systemui.shade.data.repository.ShadePositionRepository
+import com.android.systemui.shade.data.repository.ShadePositionRepositoryImpl
import com.android.systemui.shade.shared.flag.ShadeWindowGoesAround
import com.android.systemui.statusbar.phone.ConfigurationControllerImpl
import com.android.systemui.statusbar.phone.ConfigurationForwarder
import com.android.systemui.statusbar.policy.ConfigurationController
import dagger.Module
import dagger.Provides
+import dagger.multibindings.ClassKey
+import dagger.multibindings.IntoMap
/**
* Module responsible for managing display-specific components and resources for the notification
@@ -149,4 +154,25 @@ object ShadeDisplayAwareModule {
configurationInteractor
}
}
+
+ @SysUISingleton
+ @Provides
+ @ShadeDisplayAware
+ fun provideShadePositionRepository(impl: ShadePositionRepositoryImpl): ShadePositionRepository {
+ ShadeWindowGoesAround.isUnexpectedlyInLegacyMode()
+ return impl
+ }
+
+ @Provides
+ @IntoMap
+ @ClassKey(ShadePositionRepositoryImpl::class)
+ fun provideShadePositionRepositoryAsCoreStartable(
+ impl: ShadePositionRepositoryImpl
+ ): CoreStartable {
+ return if (ShadeWindowGoesAround.isEnabled) {
+ impl
+ } else {
+ CoreStartable.NOP
+ }
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadePrimaryDisplayCommand.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadePrimaryDisplayCommand.kt
new file mode 100644
index 000000000000..802fc0edb533
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadePrimaryDisplayCommand.kt
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2024 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.shade
+
+import android.view.Display
+import com.android.systemui.shade.data.repository.ShadePositionRepository
+import com.android.systemui.statusbar.commandline.Command
+import java.io.PrintWriter
+
+class ShadePrimaryDisplayCommand(private val positionRepository: ShadePositionRepository) :
+ Command {
+
+ override fun execute(pw: PrintWriter, args: List<String>) {
+ if (args[0].lowercase() == "reset") {
+ positionRepository.resetDisplayId()
+ pw.println("Reset shade primary display id to ${Display.DEFAULT_DISPLAY}")
+ return
+ }
+
+ val displayId: Int =
+ try {
+ args[0].toInt()
+ } catch (e: NumberFormatException) {
+ pw.println("Error: task id should be an integer")
+ return
+ }
+
+ if (displayId < 0) {
+ pw.println("Error: display id should be positive integer")
+ }
+
+ positionRepository.setDisplayId(displayId)
+ pw.println("New shade primary display id is $displayId")
+ }
+
+ override fun help(pw: PrintWriter) {
+ pw.println("shade_display_override <displayId> ")
+ pw.println("Set the display which is holding the shade.")
+ pw.println("shade_display_override reset ")
+ pw.println("Reset the display which is holding the shade.")
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadePositionRepository.kt b/packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadePositionRepository.kt
new file mode 100644
index 000000000000..24c067ae2371
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/shade/data/repository/ShadePositionRepository.kt
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2024 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.shade.data.repository
+
+import android.view.Display
+import com.android.systemui.CoreStartable
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.shade.ShadePrimaryDisplayCommand
+import com.android.systemui.statusbar.commandline.CommandRegistry
+import javax.inject.Inject
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+
+interface ShadePositionRepository {
+ /** ID of the display which currently hosts the shade */
+ val displayId: StateFlow<Int>
+
+ /**
+ * Updates the value of the shade display id stored, emitting to the new display id to every
+ * component dependent on the shade display id
+ */
+ fun setDisplayId(displayId: Int)
+
+ /** Resets value of shade primary display to the default display */
+ fun resetDisplayId()
+}
+
+/** Source of truth for the display currently holding the shade. */
+@SysUISingleton
+class ShadePositionRepositoryImpl
+@Inject
+constructor(private val commandRegistry: CommandRegistry) : ShadePositionRepository, CoreStartable {
+ private val _displayId = MutableStateFlow(Display.DEFAULT_DISPLAY)
+
+ override val displayId: StateFlow<Int>
+ get() = _displayId
+
+ override fun setDisplayId(displayId: Int) {
+ _displayId.value = displayId
+ }
+
+ override fun resetDisplayId() {
+ _displayId.value = Display.DEFAULT_DISPLAY
+ }
+
+ override fun start() {
+ commandRegistry.registerCommand("shade_display_override") {
+ ShadePrimaryDisplayCommand(this)
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImpl.java
index 3a31851bcb4f..52a79d39bb3b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/AccessPointControllerImpl.java
@@ -16,6 +16,9 @@
package com.android.systemui.statusbar.connectivity;
+import static com.android.systemui.Flags.multiuserWifiPickerTrackerSupport;
+
+import android.content.Context;
import android.content.Intent;
import android.os.UserHandle;
import android.os.UserManager;
@@ -65,13 +68,16 @@ public class AccessPointControllerImpl implements AccessPointController,
private final LifecycleRegistry mLifecycle = new LifecycleRegistry(this);
private int mCurrentUser;
+ private Context mContext;
public AccessPointControllerImpl(
+ Context context,
UserManager userManager,
UserTracker userTracker,
Executor mainExecutor,
WifiPickerTrackerFactory wifiPickerTrackerFactory
) {
+ mContext = context;
mUserManager = userManager;
mUserTracker = userTracker;
mCurrentUser = userTracker.getUserId();
@@ -87,7 +93,11 @@ public class AccessPointControllerImpl implements AccessPointController,
*/
public void init() {
if (mWifiPickerTracker == null) {
- mWifiPickerTracker = mWifiPickerTrackerFactory.create(this.getLifecycle(), this, TAG);
+ // We are creating the WifiPickerTracker during init to make sure we have one
+ // available at all times however we expect this to be recreated very quickly
+ // with a user-specific context in onUserSwitched.
+ mWifiPickerTracker =
+ mWifiPickerTrackerFactory.create(mContext, this.getLifecycle(), this, TAG);
}
}
@@ -116,6 +126,19 @@ public class AccessPointControllerImpl implements AccessPointController,
void onUserSwitched(int newUserId) {
mCurrentUser = newUserId;
+ // Return early if multiuser support is not enabled.
+ if (!multiuserWifiPickerTrackerSupport()) {
+ return;
+ }
+
+ if (mWifiPickerTracker != null) {
+ mMainExecutor.execute(() -> mLifecycle.setCurrentState(Lifecycle.State.CREATED));
+ }
+ Context context = mContext.createContextAsUser(UserHandle.of(newUserId), /* flags= */ 0);
+ mWifiPickerTracker = mWifiPickerTrackerFactory.create(context, mLifecycle, this, TAG);
+ if (!mCallbacks.isEmpty()) {
+ mMainExecutor.execute(() -> mLifecycle.setCurrentState(Lifecycle.State.STARTED));
+ }
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiPickerTrackerFactory.kt b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiPickerTrackerFactory.kt
index dc2ebe55fb73..947ce33274d3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiPickerTrackerFactory.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiPickerTrackerFactory.kt
@@ -22,6 +22,7 @@ import android.net.wifi.WifiManager
import android.os.Handler
import android.os.SimpleClock
import androidx.lifecycle.Lifecycle
+import com.android.systemui.Flags.multiuserWifiPickerTrackerSupport
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.util.concurrency.ThreadFactory
@@ -41,7 +42,7 @@ import javax.inject.Inject
class WifiPickerTrackerFactory
@Inject
constructor(
- private val context: Context,
+ private val applicationContext: Context,
private val wifiManager: WifiManager?,
private val connectivityManager: ConnectivityManager,
private val systemClock: SystemClock,
@@ -64,16 +65,23 @@ constructor(
* @return a new [WifiPickerTracker] or null if [WifiManager] is null.
*/
fun create(
+ userContext: Context,
lifecycle: Lifecycle,
listener: WifiPickerTrackerCallback,
name: String,
): WifiPickerTracker? {
return if (wifiManager == null) {
null
- } else
+ } else {
+ val contextToUse =
+ if (multiuserWifiPickerTrackerSupport()) {
+ userContext
+ } else {
+ applicationContext
+ }
WifiPickerTracker(
lifecycle,
- context,
+ contextToUse,
wifiManager,
connectivityManager,
mainHandler,
@@ -86,6 +94,7 @@ constructor(
SCAN_INTERVAL_MILLIS,
listener,
)
+ }
}
companion object {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/LockScreenMinimalismCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/LockScreenMinimalismCoordinator.kt
index 2fded34a56a0..e2328497d9ea 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/LockScreenMinimalismCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/LockScreenMinimalismCoordinator.kt
@@ -19,6 +19,7 @@ package com.android.systemui.statusbar.notification.collection.coordinator
import android.annotation.SuppressLint
import android.app.NotificationManager
import androidx.annotation.VisibleForTesting
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.Dumpable
import com.android.systemui.dagger.qualifiers.Application
import com.android.systemui.dump.DumpManager
@@ -50,7 +51,6 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
-import com.android.app.tracing.coroutines.launchTraced as launch
/**
* If the setting is enabled, this will track seen notifications and ensure that they only show in
@@ -74,7 +74,7 @@ constructor(
private val unseenNotifications = mutableSetOf<NotificationEntry>()
private var isShadeVisible = false
- private var unseenFilterEnabled = false
+ private var minimalismEnabled = false
override fun attach(pipeline: NotifPipeline) {
if (NotificationMinimalism.isUnexpectedlyInLegacyMode()) {
@@ -83,7 +83,7 @@ constructor(
pipeline.addPromoter(unseenNotifPromoter)
pipeline.addOnBeforeTransformGroupsListener(::pickOutTopUnseenNotifs)
pipeline.addCollectionListener(collectionListener)
- scope.launch { trackUnseenFilterSettingChanges() }
+ scope.launch { trackLockScreenNotificationMinimalismSettingChanges() }
dumpManager.registerDumpable(this)
}
@@ -136,12 +136,12 @@ constructor(
return seenNotificationsInteractor.isLockScreenNotificationMinimalismEnabled()
}
- private suspend fun trackUnseenFilterSettingChanges() {
+ private suspend fun trackLockScreenNotificationMinimalismSettingChanges() {
// Only filter the seen notifs when the lock screen minimalism feature settings is on.
minimalismFeatureSettingEnabled().collectLatest { isMinimalismSettingEnabled ->
// update local field and invalidate if necessary
- if (isMinimalismSettingEnabled != unseenFilterEnabled) {
- unseenFilterEnabled = isMinimalismSettingEnabled
+ if (isMinimalismSettingEnabled != minimalismEnabled) {
+ minimalismEnabled = isMinimalismSettingEnabled
unseenNotifications.clear()
unseenNotifPromoter.invalidateList("unseen setting changed")
}
@@ -156,21 +156,21 @@ constructor(
private val collectionListener =
object : NotifCollectionListener {
override fun onEntryAdded(entry: NotificationEntry) {
- if (unseenFilterEnabled && !isShadeVisible) {
+ if (minimalismEnabled && !isShadeVisible) {
logger.logUnseenAdded(entry.key)
unseenNotifications.add(entry)
}
}
override fun onEntryUpdated(entry: NotificationEntry) {
- if (unseenFilterEnabled && !isShadeVisible) {
+ if (minimalismEnabled && !isShadeVisible) {
logger.logUnseenUpdated(entry.key)
unseenNotifications.add(entry)
}
}
override fun onEntryRemoved(entry: NotificationEntry, reason: Int) {
- if (unseenFilterEnabled && unseenNotifications.remove(entry)) {
+ if (minimalismEnabled && unseenNotifications.remove(entry)) {
logger.logUnseenRemoved(entry.key)
}
}
@@ -178,7 +178,7 @@ constructor(
private fun pickOutTopUnseenNotifs(list: List<ListEntry>) {
if (NotificationMinimalism.isUnexpectedlyInLegacyMode()) return
- if (!unseenFilterEnabled) return
+ if (!minimalismEnabled) return
// Only ever elevate a top unseen notification on keyguard, not even locked shade
if (statusBarStateController.state != StatusBarState.KEYGUARD) {
seenNotificationsInteractor.setTopOngoingNotification(null)
@@ -215,6 +215,7 @@ constructor(
override fun shouldPromoteToTopLevel(child: NotificationEntry): Boolean =
when {
NotificationMinimalism.isUnexpectedlyInLegacyMode() -> false
+ !minimalismEnabled -> false
seenNotificationsInteractor.isTopOngoingNotification(child) -> true
!NotificationMinimalism.ungroupTopUnseen -> false
else -> seenNotificationsInteractor.isTopUnseenNotification(child)
@@ -225,6 +226,7 @@ constructor(
object : NotifSectioner("TopOngoing", BUCKET_TOP_ONGOING) {
override fun isInSection(entry: ListEntry): Boolean {
if (NotificationMinimalism.isUnexpectedlyInLegacyMode()) return false
+ if (!minimalismEnabled) return false
return entry.anyEntry { notificationEntry ->
seenNotificationsInteractor.isTopOngoingNotification(notificationEntry)
}
@@ -235,6 +237,7 @@ constructor(
object : NotifSectioner("TopUnseen", BUCKET_TOP_UNSEEN) {
override fun isInSection(entry: ListEntry): Boolean {
if (NotificationMinimalism.isUnexpectedlyInLegacyMode()) return false
+ if (!minimalismEnabled) return false
return entry.anyEntry { notificationEntry ->
seenNotificationsInteractor.isTopUnseenNotification(notificationEntry)
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculator.kt
index 3bc549543ef2..5dff8120f33f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackSizeCalculator.kt
@@ -21,12 +21,14 @@ import android.util.Log
import android.view.View.GONE
import androidx.annotation.VisibleForTesting
import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Application
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.media.controls.domain.pipeline.MediaDataManager
import com.android.systemui.res.R
import com.android.systemui.statusbar.LockscreenShadeTransitionController
import com.android.systemui.statusbar.StatusBarState.KEYGUARD
import com.android.systemui.statusbar.SysuiStatusBarStateController
+import com.android.systemui.statusbar.notification.domain.interactor.SeenNotificationsInteractor
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow
import com.android.systemui.statusbar.notification.row.ExpandableView
import com.android.systemui.statusbar.notification.shared.NotificationMinimalism
@@ -38,6 +40,9 @@ import javax.inject.Inject
import kotlin.math.max
import kotlin.math.min
import kotlin.properties.Delegates.notNull
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.launch
private const val TAG = "NotifStackSizeCalc"
private val DEBUG = Compile.IS_DEBUG && Log.isLoggable(TAG, Log.DEBUG)
@@ -56,7 +61,9 @@ constructor(
private val lockscreenShadeTransitionController: LockscreenShadeTransitionController,
private val mediaDataManager: MediaDataManager,
@Main private val resources: Resources,
- private val splitShadeStateController: SplitShadeStateController
+ private val splitShadeStateController: SplitShadeStateController,
+ private val seenNotificationsInteractor: SeenNotificationsInteractor,
+ @Application private val scope: CoroutineScope,
) {
/**
@@ -74,7 +81,7 @@ constructor(
/** Whether we allow keyguard to show less important notifications above the shelf. */
private val limitLockScreenToOneImportant
- get() = NotificationMinimalism.isEnabled
+ get() = NotificationMinimalism.isEnabled && minimalismSettingEnabled
/** Minimum space between two notifications, see [calculateGapAndDividerHeight]. */
private var dividerHeight by notNull<Float>()
@@ -85,8 +92,14 @@ constructor(
*/
private var saveSpaceOnLockscreen = false
+ /** True when the lock screen notification minimalism feature setting is enabled */
+ private var minimalismSettingEnabled = false
+
init {
updateResources()
+ if (NotificationMinimalism.isEnabled) {
+ scope.launch { trackLockScreenNotificationMinimalismSettingChanges() }
+ }
}
private fun allowedByPolicy(stackHeight: StackHeight): Boolean =
@@ -199,7 +212,7 @@ constructor(
canStackFitInSpace(
heightResult,
notifSpace = notifSpace,
- shelfSpace = shelfSpace
+ shelfSpace = shelfSpace,
) == FitResult.FIT
}
@@ -229,7 +242,7 @@ constructor(
canStackFitInSpace(
heightResult,
notifSpace = notifSpace,
- shelfSpace = shelfSpace
+ shelfSpace = shelfSpace,
) != FitResult.NO_FIT
}
log { "\t--- maxNotifications=$maxNotifications" }
@@ -277,7 +290,7 @@ constructor(
fun computeHeight(
stack: NotificationStackScrollLayout,
maxNotifs: Int,
- shelfHeight: Float
+ shelfHeight: Float,
): Float {
log { "\n" }
log { "computeHeight ---" }
@@ -311,7 +324,7 @@ constructor(
private enum class FitResult {
FIT,
FIT_IF_SAVE_SPACE,
- NO_FIT
+ NO_FIT,
}
data class SpaceNeeded(
@@ -319,7 +332,7 @@ constructor(
val whenEnoughSpace: Float,
// Float height of space needed when showing collapsed layout for FSI HUNs.
- val whenSavingSpace: Float
+ val whenSavingSpace: Float,
)
private data class StackHeight(
@@ -335,9 +348,19 @@ constructor(
val shelfHeightWithSpaceBefore: Float,
/** Whether the stack should actually be forced into the shelf before this height. */
- val shouldForceIntoShelf: Boolean
+ val shouldForceIntoShelf: Boolean,
)
+ private suspend fun trackLockScreenNotificationMinimalismSettingChanges() {
+ if (NotificationMinimalism.isUnexpectedlyInLegacyMode()) return
+ seenNotificationsInteractor.isLockScreenNotificationMinimalismEnabled().collectLatest {
+ if (it != minimalismSettingEnabled) {
+ minimalismSettingEnabled = it
+ }
+ Log.i(TAG, "minimalismSettingEnabled: $minimalismSettingEnabled")
+ }
+ }
+
private fun computeHeightPerNotificationLimit(
stack: NotificationStackScrollLayout,
shelfHeight: Float,
@@ -377,7 +400,7 @@ constructor(
stack,
previous = currentNotification,
current = children[firstViewInShelfIndex],
- currentIndex = firstViewInShelfIndex
+ currentIndex = firstViewInShelfIndex,
)
spaceBeforeShelf + shelfHeight
}
@@ -390,14 +413,15 @@ constructor(
log {
"\tcomputeHeightPerNotificationLimit i=$i notifs=$notifications " +
"notifsHeightSavingSpace=$notifsWithCollapsedHun" +
- " shelfWithSpaceBefore=$shelfWithSpaceBefore"
+ " shelfWithSpaceBefore=$shelfWithSpaceBefore" +
+ " limitLockScreenToOneImportant: $limitLockScreenToOneImportant"
}
yield(
StackHeight(
notifsHeight = notifications,
notifsHeightSavingSpace = notifsWithCollapsedHun,
shelfHeightWithSpaceBefore = shelfWithSpaceBefore,
- shouldForceIntoShelf = counter?.shouldForceIntoShelf() ?: false
+ shouldForceIntoShelf = counter?.shouldForceIntoShelf() ?: false,
)
)
}
@@ -462,6 +486,10 @@ constructor(
fun dump(pw: PrintWriter, args: Array<out String>) {
pw.println("NotificationStackSizeCalculator saveSpaceOnLockscreen=$saveSpaceOnLockscreen")
+ pw.println(
+ "NotificationStackSizeCalculator " +
+ "limitLockScreenToOneImportant=$limitLockScreenToOneImportant"
+ )
}
private fun ExpandableView.isShowable(onLockscreen: Boolean): Boolean {
@@ -484,7 +512,7 @@ constructor(
stack: NotificationStackScrollLayout,
previous: ExpandableView?,
current: ExpandableView?,
- currentIndex: Int
+ currentIndex: Int,
): Float {
if (currentIndex == 0) {
return 0f
@@ -536,11 +564,7 @@ constructor(
takeWhile(predicate).count() - 1
/** Counts the number of notifications for each type of bucket */
- data class BucketTypeCounter(
- var ongoing: Int = 0,
- var important: Int = 0,
- var other: Int = 0,
- ) {
+ data class BucketTypeCounter(var ongoing: Int = 0, var important: Int = 0, var other: Int = 0) {
fun incrementForBucket(@PriorityBucket bucket: Int?) {
when (bucket) {
BUCKET_MEDIA_CONTROLS,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/MobileInputLogger.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/MobileInputLogger.kt
index 9cbfc440ab16..94e9d26c9dc8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/MobileInputLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/MobileInputLogger.kt
@@ -21,6 +21,7 @@ import android.telephony.ServiceState
import android.telephony.SignalStrength
import android.telephony.TelephonyDisplayInfo
import android.telephony.TelephonyManager
+import android.telephony.satellite.NtnSignalStrength
import com.android.settingslib.SignalIcon
import com.android.settingslib.mobile.MobileMappings
import com.android.systemui.dagger.SysUISingleton
@@ -31,11 +32,7 @@ import javax.inject.Inject
/** Logs for inputs into the mobile pipeline. */
@SysUISingleton
-class MobileInputLogger
-@Inject
-constructor(
- @MobileInputLog private val buffer: LogBuffer,
-) {
+class MobileInputLogger @Inject constructor(@MobileInputLog private val buffer: LogBuffer) {
fun logOnServiceStateChanged(serviceState: ServiceState, subId: Int) {
buffer.log(
TAG,
@@ -49,7 +46,7 @@ constructor(
{
"onServiceStateChanged: subId=$int1 emergencyOnly=$bool1 roaming=$bool2" +
" operator=$str1"
- }
+ },
)
}
@@ -61,7 +58,7 @@ constructor(
int1 = subId
bool1 = serviceState.isEmergencyOnly
},
- { "ACTION_SERVICE_STATE for subId=$int1. ServiceState.isEmergencyOnly=$bool1" }
+ { "ACTION_SERVICE_STATE for subId=$int1. ServiceState.isEmergencyOnly=$bool1" },
)
}
@@ -70,7 +67,7 @@ constructor(
TAG,
LogLevel.INFO,
{ int1 = subId },
- { "ACTION_SERVICE_STATE for subId=$int1. Intent is missing extras. Ignoring" }
+ { "ACTION_SERVICE_STATE for subId=$int1. Intent is missing extras. Ignoring" },
)
}
@@ -82,7 +79,16 @@ constructor(
int1 = subId
str1 = signalStrength.toString()
},
- { "onSignalStrengthsChanged: subId=$int1 strengths=$str1" }
+ { "onSignalStrengthsChanged: subId=$int1 strengths=$str1" },
+ )
+ }
+
+ fun logNtnSignalStrengthChanged(signalStrength: NtnSignalStrength) {
+ buffer.log(
+ TAG,
+ LogLevel.INFO,
+ { int1 = signalStrength.level },
+ { "onCarrierRoamingNtnSignalStrengthChanged: level=$int1" },
)
}
@@ -128,7 +134,7 @@ constructor(
TAG,
LogLevel.INFO,
{ bool1 = active },
- { "onCarrierRoamingNtnModeChanged: $bool1" }
+ { "onCarrierRoamingNtnModeChanged: $bool1" },
)
}
@@ -146,12 +152,7 @@ constructor(
}
fun logCarrierConfigChanged(subId: Int) {
- buffer.log(
- TAG,
- LogLevel.INFO,
- { int1 = subId },
- { "onCarrierConfigChanged: subId=$int1" },
- )
+ buffer.log(TAG, LogLevel.INFO, { int1 = subId }, { "onCarrierConfigChanged: subId=$int1" })
}
fun logOnDataEnabledChanged(enabled: Boolean, subId: Int) {
@@ -175,7 +176,7 @@ constructor(
TAG,
LogLevel.INFO,
{ str1 = config.toString() },
- { "defaultDataSubRatConfig: $str1" }
+ { "defaultDataSubRatConfig: $str1" },
)
}
@@ -184,7 +185,7 @@ constructor(
TAG,
LogLevel.INFO,
{ str1 = mapping.toString() },
- { "defaultMobileIconMapping: $str1" }
+ { "defaultMobileIconMapping: $str1" },
)
}
@@ -216,7 +217,7 @@ constructor(
{
"Intent: ACTION_SERVICE_PROVIDERS_UPDATED." +
" showSpn=$bool1 spn=$str1 dataSpn=$str2 showPlmn=$bool2 plmn=$str3"
- }
+ },
)
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
index 205205eac210..07843f1ef041 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt
@@ -107,6 +107,12 @@ interface MobileConnectionRepository {
// @IntRange(from = 0, to = 4)
val primaryLevel: StateFlow<Int>
+ /**
+ * This level can be used to reflect the signal strength when in carrier roaming NTN mode
+ * (carrier-based satellite)
+ */
+ val satelliteLevel: StateFlow<Int>
+
/** The current data connection state. See [DataConnectionState] */
val dataConnectionState: StateFlow<DataConnectionState>
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
index 3261b71ece3c..be3977ecd4ba 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionRepository.kt
@@ -37,12 +37,14 @@ import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.FullM
import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.FullMobileConnectionRepository.Companion.COL_OPERATOR
import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.FullMobileConnectionRepository.Companion.COL_PRIMARY_LEVEL
import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.FullMobileConnectionRepository.Companion.COL_ROAMING
+import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.FullMobileConnectionRepository.Companion.COL_SATELLITE_LEVEL
import com.android.systemui.statusbar.pipeline.shared.data.model.DataActivityModel
import com.android.systemui.statusbar.pipeline.shared.data.model.toMobileDataActivityModel
import com.android.systemui.statusbar.pipeline.wifi.data.repository.demo.model.FakeWifiEventModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
@@ -75,7 +77,7 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = "inflate",
- _inflateSignalStrength.value
+ _inflateSignalStrength.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _inflateSignalStrength.value)
@@ -89,7 +91,7 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_EMERGENCY,
- _isEmergencyOnly.value
+ _isEmergencyOnly.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _isEmergencyOnly.value)
@@ -100,7 +102,7 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_ROAMING,
- _isRoaming.value
+ _isRoaming.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _isRoaming.value)
@@ -111,7 +113,7 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_OPERATOR,
- _operatorAlphaShort.value
+ _operatorAlphaShort.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _operatorAlphaShort.value)
@@ -122,7 +124,7 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_IS_IN_SERVICE,
- _isInService.value
+ _isInService.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _isInService.value)
@@ -133,7 +135,7 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_IS_NTN,
- _isNonTerrestrial.value
+ _isNonTerrestrial.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _isNonTerrestrial.value)
@@ -144,7 +146,7 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_IS_GSM,
- _isGsm.value
+ _isGsm.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _isGsm.value)
@@ -155,7 +157,7 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_CDMA_LEVEL,
- _cdmaLevel.value
+ _cdmaLevel.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _cdmaLevel.value)
@@ -166,10 +168,21 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_PRIMARY_LEVEL,
- _primaryLevel.value
+ _primaryLevel.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _primaryLevel.value)
+ private val _satelliteLevel = MutableStateFlow(0)
+ override val satelliteLevel: StateFlow<Int> =
+ _satelliteLevel
+ .logDiffsForTable(
+ tableLogBuffer,
+ columnPrefix = "",
+ columnName = COL_SATELLITE_LEVEL,
+ _satelliteLevel.value,
+ )
+ .stateIn(scope, SharingStarted.WhileSubscribed(), _satelliteLevel.value)
+
private val _dataConnectionState = MutableStateFlow(DataConnectionState.Disconnected)
override val dataConnectionState =
_dataConnectionState
@@ -177,12 +190,7 @@ class DemoMobileConnectionRepository(
.stateIn(scope, SharingStarted.WhileSubscribed(), _dataConnectionState.value)
private val _dataActivityDirection =
- MutableStateFlow(
- DataActivityModel(
- hasActivityIn = false,
- hasActivityOut = false,
- )
- )
+ MutableStateFlow(DataActivityModel(hasActivityIn = false, hasActivityOut = false))
override val dataActivityDirection =
_dataActivityDirection
.logDiffsForTable(tableLogBuffer, columnPrefix = "", _dataActivityDirection.value)
@@ -195,7 +203,7 @@ class DemoMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_CARRIER_NETWORK_CHANGE,
- _carrierNetworkChangeActive.value
+ _carrierNetworkChangeActive.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), _carrierNetworkChangeActive.value)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt
index 2e4767893c3d..75f613d7e3c6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/CarrierMergedConnectionRepository.kt
@@ -90,7 +90,7 @@ class CarrierMergedConnectionRepository(
TAG,
"Connection repo subId=$subId " +
"does not equal wifi repo subId=${network.subscriptionId}; " +
- "not showing carrier merged"
+ "not showing carrier merged",
)
null
}
@@ -149,7 +149,7 @@ class CarrierMergedConnectionRepository(
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- ResolvedNetworkType.UnknownNetworkType
+ ResolvedNetworkType.UnknownNetworkType,
)
override val dataConnectionState =
@@ -173,6 +173,7 @@ class CarrierMergedConnectionRepository(
override val isNonTerrestrial = MutableStateFlow(false).asStateFlow()
override val isGsm = MutableStateFlow(false).asStateFlow()
override val carrierNetworkChangeActive = MutableStateFlow(false).asStateFlow()
+ override val satelliteLevel = MutableStateFlow(0)
/**
* Carrier merged connections happen over wifi but are displayed as a mobile triangle. Because
@@ -207,10 +208,7 @@ class CarrierMergedConnectionRepository(
@Application private val scope: CoroutineScope,
private val wifiRepository: WifiRepository,
) {
- fun build(
- subId: Int,
- mobileLogger: TableLogBuffer,
- ): MobileConnectionRepository {
+ fun build(subId: Int, mobileLogger: TableLogBuffer): MobileConnectionRepository {
return CarrierMergedConnectionRepository(
subId,
mobileLogger,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt
index a5e47a6e68cd..fae9be083e12 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/FullMobileConnectionRepository.kt
@@ -132,12 +132,12 @@ class FullMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_EMERGENCY,
- activeRepo.value.isEmergencyOnly.value
+ activeRepo.value.isEmergencyOnly.value,
)
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- activeRepo.value.isEmergencyOnly.value
+ activeRepo.value.isEmergencyOnly.value,
)
override val isRoaming =
@@ -147,7 +147,7 @@ class FullMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_ROAMING,
- activeRepo.value.isRoaming.value
+ activeRepo.value.isRoaming.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), activeRepo.value.isRoaming.value)
@@ -158,12 +158,12 @@ class FullMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_OPERATOR,
- activeRepo.value.operatorAlphaShort.value
+ activeRepo.value.operatorAlphaShort.value,
)
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- activeRepo.value.operatorAlphaShort.value
+ activeRepo.value.operatorAlphaShort.value,
)
override val isInService =
@@ -173,7 +173,7 @@ class FullMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_IS_IN_SERVICE,
- activeRepo.value.isInService.value
+ activeRepo.value.isInService.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), activeRepo.value.isInService.value)
@@ -184,12 +184,12 @@ class FullMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_IS_NTN,
- activeRepo.value.isNonTerrestrial.value
+ activeRepo.value.isNonTerrestrial.value,
)
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- activeRepo.value.isNonTerrestrial.value
+ activeRepo.value.isNonTerrestrial.value,
)
override val isGsm =
@@ -199,7 +199,7 @@ class FullMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_IS_GSM,
- activeRepo.value.isGsm.value
+ activeRepo.value.isGsm.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), activeRepo.value.isGsm.value)
@@ -210,7 +210,7 @@ class FullMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_CDMA_LEVEL,
- activeRepo.value.cdmaLevel.value
+ activeRepo.value.cdmaLevel.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), activeRepo.value.cdmaLevel.value)
@@ -221,22 +221,33 @@ class FullMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_PRIMARY_LEVEL,
- activeRepo.value.primaryLevel.value
+ activeRepo.value.primaryLevel.value,
)
.stateIn(scope, SharingStarted.WhileSubscribed(), activeRepo.value.primaryLevel.value)
+ override val satelliteLevel: StateFlow<Int> =
+ activeRepo
+ .flatMapLatest { it.satelliteLevel }
+ .logDiffsForTable(
+ tableLogBuffer,
+ columnPrefix = "",
+ columnName = COL_SATELLITE_LEVEL,
+ activeRepo.value.satelliteLevel.value,
+ )
+ .stateIn(scope, SharingStarted.WhileSubscribed(), activeRepo.value.satelliteLevel.value)
+
override val dataConnectionState =
activeRepo
.flatMapLatest { it.dataConnectionState }
.logDiffsForTable(
tableLogBuffer,
columnPrefix = "",
- activeRepo.value.dataConnectionState.value
+ activeRepo.value.dataConnectionState.value,
)
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- activeRepo.value.dataConnectionState.value
+ activeRepo.value.dataConnectionState.value,
)
override val dataActivityDirection =
@@ -245,12 +256,12 @@ class FullMobileConnectionRepository(
.logDiffsForTable(
tableLogBuffer,
columnPrefix = "",
- activeRepo.value.dataActivityDirection.value
+ activeRepo.value.dataActivityDirection.value,
)
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- activeRepo.value.dataActivityDirection.value
+ activeRepo.value.dataActivityDirection.value,
)
override val carrierNetworkChangeActive =
@@ -260,12 +271,12 @@ class FullMobileConnectionRepository(
tableLogBuffer,
columnPrefix = "",
columnName = COL_CARRIER_NETWORK_CHANGE,
- activeRepo.value.carrierNetworkChangeActive.value
+ activeRepo.value.carrierNetworkChangeActive.value,
)
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- activeRepo.value.carrierNetworkChangeActive.value
+ activeRepo.value.carrierNetworkChangeActive.value,
)
override val resolvedNetworkType =
@@ -274,12 +285,12 @@ class FullMobileConnectionRepository(
.logDiffsForTable(
tableLogBuffer,
columnPrefix = "",
- activeRepo.value.resolvedNetworkType.value
+ activeRepo.value.resolvedNetworkType.value,
)
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- activeRepo.value.resolvedNetworkType.value
+ activeRepo.value.resolvedNetworkType.value,
)
override val dataEnabled =
@@ -305,7 +316,7 @@ class FullMobileConnectionRepository(
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- activeRepo.value.inflateSignalStrength.value
+ activeRepo.value.inflateSignalStrength.value,
)
override val allowNetworkSliceIndicator =
@@ -320,7 +331,7 @@ class FullMobileConnectionRepository(
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- activeRepo.value.allowNetworkSliceIndicator.value
+ activeRepo.value.allowNetworkSliceIndicator.value,
)
override val numberOfLevels =
@@ -439,6 +450,7 @@ class FullMobileConnectionRepository(
const val COL_IS_IN_SERVICE = "isInService"
const val COL_OPERATOR = "operatorName"
const val COL_PRIMARY_LEVEL = "primaryLevel"
+ const val COL_SATELLITE_LEVEL = "satelliteLevel"
const val COL_ROAMING = "roaming"
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt
index 62bd8ad4317c..8a1e7f9a0096 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt
@@ -41,6 +41,7 @@ import android.telephony.TelephonyManager.ERI_ON
import android.telephony.TelephonyManager.EXTRA_SUBSCRIPTION_ID
import android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN
import android.telephony.TelephonyManager.UNKNOWN_CARRIER_ID
+import android.telephony.satellite.NtnSignalStrength
import com.android.settingslib.Utils
import com.android.systemui.broadcast.BroadcastDispatcher
import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
@@ -173,7 +174,7 @@ class MobileConnectionRepositoryImpl(
override fun onDataConnectionStateChanged(
dataState: Int,
- networkType: Int
+ networkType: Int,
) {
logger.logOnDataConnectionStateChanged(dataState, networkType, subId)
trySend(CallbackEvent.OnDataConnectionStateChanged(dataState))
@@ -195,6 +196,17 @@ class MobileConnectionRepositoryImpl(
logger.logOnSignalStrengthsChanged(signalStrength, subId)
trySend(CallbackEvent.OnSignalStrengthChanged(signalStrength))
}
+
+ override fun onCarrierRoamingNtnSignalStrengthChanged(
+ signalStrength: NtnSignalStrength
+ ) {
+ logger.logNtnSignalStrengthChanged(signalStrength)
+ trySend(
+ CallbackEvent.OnCarrierRoamingNtnSignalStrengthChanged(
+ signalStrength
+ )
+ )
+ }
}
telephonyManager.registerTelephonyCallback(bgDispatcher.asExecutor(), callback)
awaitClose { telephonyManager.unregisterTelephonyCallback(callback) }
@@ -267,6 +279,12 @@ class MobileConnectionRepositoryImpl(
.map { it.signalStrength.level }
.stateIn(scope, SharingStarted.WhileSubscribed(), SIGNAL_STRENGTH_NONE_OR_UNKNOWN)
+ override val satelliteLevel: StateFlow<Int> =
+ callbackEvents
+ .mapNotNull { it.onCarrierRoamingNtnSignalStrengthChanged }
+ .map { it.signalStrength.level }
+ .stateIn(scope, SharingStarted.WhileSubscribed(), 0)
+
override val dataConnectionState =
callbackEvents
.mapNotNull { it.onDataConnectionStateChanged }
@@ -280,7 +298,7 @@ class MobileConnectionRepositoryImpl(
.stateIn(
scope,
SharingStarted.WhileSubscribed(),
- DataActivityModel(hasActivityIn = false, hasActivityOut = false)
+ DataActivityModel(hasActivityIn = false, hasActivityOut = false),
)
override val carrierNetworkChangeActive =
@@ -385,7 +403,7 @@ class MobileConnectionRepositoryImpl(
if (
intent.getIntExtra(
EXTRA_SUBSCRIPTION_INDEX,
- INVALID_SUBSCRIPTION_ID
+ INVALID_SUBSCRIPTION_ID,
) == subId
) {
logger.logServiceProvidersUpdatedBroadcast(intent)
@@ -399,7 +417,7 @@ class MobileConnectionRepositoryImpl(
context.registerReceiver(
receiver,
- IntentFilter(TelephonyManager.ACTION_SERVICE_PROVIDERS_UPDATED)
+ IntentFilter(TelephonyManager.ACTION_SERVICE_PROVIDERS_UPDATED),
)
awaitClose { context.unregisterReceiver(receiver) }
@@ -524,6 +542,9 @@ sealed interface CallbackEvent {
data class OnServiceStateChanged(val serviceState: ServiceState) : CallbackEvent
data class OnSignalStrengthChanged(val signalStrength: SignalStrength) : CallbackEvent
+
+ data class OnCarrierRoamingNtnSignalStrengthChanged(val signalStrength: NtnSignalStrength) :
+ CallbackEvent
}
/**
@@ -539,6 +560,9 @@ data class TelephonyCallbackState(
val onDisplayInfoChanged: CallbackEvent.OnDisplayInfoChanged? = null,
val onServiceStateChanged: CallbackEvent.OnServiceStateChanged? = null,
val onSignalStrengthChanged: CallbackEvent.OnSignalStrengthChanged? = null,
+ val onCarrierRoamingNtnSignalStrengthChanged:
+ CallbackEvent.OnCarrierRoamingNtnSignalStrengthChanged? =
+ null,
) {
fun applyEvent(event: CallbackEvent): TelephonyCallbackState {
return when (event) {
@@ -555,6 +579,8 @@ data class TelephonyCallbackState(
copy(onServiceStateChanged = event)
}
is CallbackEvent.OnSignalStrengthChanged -> copy(onSignalStrengthChanged = event)
+ is CallbackEvent.OnCarrierRoamingNtnSignalStrengthChanged ->
+ copy(onCarrierRoamingNtnSignalStrengthChanged = event)
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
index 4ef328cf1623..1bf14af7ea6e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt
@@ -335,7 +335,11 @@ class MobileIconInteractorImpl(
// Satellite level is unaffected by the inflateSignalStrength property
// See b/346904529 for details
private val satelliteShownLevel: StateFlow<Int> =
- combine(level, isInService) { level, isInService -> if (isInService) level else 0 }
+ if (Flags.carrierRoamingNbIotNtn()) {
+ connectionRepository.satelliteLevel
+ } else {
+ combine(level, isInService) { level, isInService -> if (isInService) level else 0 }
+ }
.stateIn(scope, SharingStarted.WhileSubscribed(), 0)
private val cellularIcon: Flow<SignalIconModel.Cellular> =
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt
index 76024cd565d1..c7b6be3fc4ac 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImpl.kt
@@ -17,12 +17,15 @@
package com.android.systemui.statusbar.pipeline.wifi.data.repository.prod
import android.annotation.SuppressLint
+import android.content.Context
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
+import android.os.UserHandle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.android.internal.annotations.VisibleForTesting
+import com.android.systemui.Flags.multiuserWifiPickerTrackerSupport
import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Application
@@ -43,6 +46,7 @@ import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiReposito
import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel
import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel.Unavailable.toHotspotDeviceType
import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiScanEntry
+import com.android.systemui.user.data.repository.UserRepository
import com.android.wifitrackerlib.HotspotNetworkEntry
import com.android.wifitrackerlib.MergedCarrierEntry
import com.android.wifitrackerlib.WifiEntry
@@ -53,10 +57,12 @@ import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asExecutor
import kotlinx.coroutines.channels.awaitClose
+import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
@@ -68,6 +74,8 @@ import kotlinx.coroutines.flow.stateIn
class WifiRepositoryImpl
@Inject
constructor(
+ @Application applicationContext: Context,
+ private val userRepository: UserRepository,
@Application private val scope: CoroutineScope,
@Main private val mainExecutor: Executor,
@Background private val bgDispatcher: CoroutineDispatcher,
@@ -84,90 +92,226 @@ constructor(
private var wifiPickerTracker: WifiPickerTracker? = null
- private val wifiPickerTrackerInfo: StateFlow<WifiPickerTrackerInfo> = run {
- var current =
- WifiPickerTrackerInfo(
- state = WIFI_STATE_DEFAULT,
- isDefault = false,
- primaryNetwork = WIFI_NETWORK_DEFAULT,
- secondaryNetworks = emptyList(),
- )
- callbackFlow {
- val callback =
- object : WifiPickerTracker.WifiPickerTrackerCallback {
- override fun onWifiEntriesChanged() {
- val connectedEntry = wifiPickerTracker.mergedOrPrimaryConnection
- logOnWifiEntriesChanged(connectedEntry)
-
- val activeNetworks = wifiPickerTracker?.activeWifiEntries ?: emptyList()
- val secondaryNetworks =
- activeNetworks
- .filter { it != connectedEntry && !it.isPrimaryNetwork }
- .map { it.toWifiNetworkModel() }
-
- // [WifiPickerTracker.connectedWifiEntry] will return the same instance
- // but with updated internals. For example, when its validation status
- // changes from false to true, the same instance is re-used but with the
- // validated field updated.
- //
- // Because it's the same instance, the flow won't re-emit the value
- // (even though the internals have changed). So, we need to transform it
- // into our internal model immediately. [toWifiNetworkModel] always
- // returns a new instance, so the flow is guaranteed to emit.
- send(
- newPrimaryNetwork =
- connectedEntry?.toPrimaryWifiNetworkModel()
- ?: WIFI_NETWORK_DEFAULT,
- newSecondaryNetworks = secondaryNetworks,
- newIsDefault = connectedEntry?.isDefaultNetwork ?: false,
- )
- }
+ @VisibleForTesting
+ val selectedUserContext: Flow<Context> =
+ userRepository.selectedUserInfo.map {
+ applicationContext.createContextAsUser(UserHandle.of(it.id), /* flags= */ 0)
+ }
- override fun onWifiStateChanged() {
- val state = wifiPickerTracker?.wifiState
- logOnWifiStateChanged(state)
- send(newState = state ?: WIFI_STATE_DEFAULT)
- }
+ var current =
+ WifiPickerTrackerInfo(
+ state = WIFI_STATE_DEFAULT,
+ isDefault = false,
+ primaryNetwork = WIFI_NETWORK_DEFAULT,
+ secondaryNetworks = emptyList(),
+ )
- override fun onNumSavedNetworksChanged() {}
-
- override fun onNumSavedSubscriptionsChanged() {}
-
- private fun send(
- newState: Int = current.state,
- newIsDefault: Boolean = current.isDefault,
- newPrimaryNetwork: WifiNetworkModel = current.primaryNetwork,
- newSecondaryNetworks: List<WifiNetworkModel> =
- current.secondaryNetworks,
- ) {
- val new =
- WifiPickerTrackerInfo(
- newState,
- newIsDefault,
- newPrimaryNetwork,
- newSecondaryNetworks,
- )
- current = new
- trySend(new)
+ @kotlinx.coroutines.ExperimentalCoroutinesApi
+ private val wifiPickerTrackerInfo: StateFlow<WifiPickerTrackerInfo> =
+ if (multiuserWifiPickerTrackerSupport()) {
+ selectedUserContext
+ .flatMapLatest { currentContext
+ -> // flatMapLatest because when selectedUserContext emits a new value, we want
+ // to
+ // re-create a whole flow
+ callbackFlow {
+ val callback =
+ object : WifiPickerTracker.WifiPickerTrackerCallback {
+ override fun onWifiEntriesChanged() {
+ val connectedEntry =
+ wifiPickerTracker.mergedOrPrimaryConnection
+ logOnWifiEntriesChanged(connectedEntry)
+
+ val activeNetworks =
+ wifiPickerTracker?.activeWifiEntries ?: emptyList()
+ val secondaryNetworks =
+ activeNetworks
+ .filter {
+ it != connectedEntry && !it.isPrimaryNetwork
+ }
+ .map { it.toWifiNetworkModel() }
+
+ // [WifiPickerTracker.connectedWifiEntry] will return the
+ // same
+ // instance but with updated internals. For example, when
+ // its
+ // validation status changes from false to true, the same
+ // instance is re-used but with the validated field updated.
+ //
+ // Because it's the same instance, the flow won't re-emit
+ // the
+ // value (even though the internals have changed). So, we
+ // need
+ // to transform it into our internal model immediately.
+ // [toWifiNetworkModel] always returns a new instance, so
+ // the
+ // flow is guaranteed to emit.
+ send(
+ newPrimaryNetwork =
+ connectedEntry?.toPrimaryWifiNetworkModel()
+ ?: WIFI_NETWORK_DEFAULT,
+ newSecondaryNetworks = secondaryNetworks,
+ newIsDefault = connectedEntry?.isDefaultNetwork ?: false,
+ )
+ }
+
+ override fun onWifiStateChanged() {
+ val state = wifiPickerTracker?.wifiState
+ logOnWifiStateChanged(state)
+ send(newState = state ?: WIFI_STATE_DEFAULT)
+ }
+
+ override fun onNumSavedNetworksChanged() {}
+
+ override fun onNumSavedSubscriptionsChanged() {}
+
+ private fun send(
+ newState: Int = current.state,
+ newIsDefault: Boolean = current.isDefault,
+ newPrimaryNetwork: WifiNetworkModel =
+ current.primaryNetwork,
+ newSecondaryNetworks: List<WifiNetworkModel> =
+ current.secondaryNetworks,
+ ) {
+ val new =
+ WifiPickerTrackerInfo(
+ newState,
+ newIsDefault,
+ newPrimaryNetwork,
+ newSecondaryNetworks,
+ )
+ current = new
+ trySend(new)
+ }
+ }
+ wifiPickerTracker =
+ wifiPickerTrackerFactory
+ .create(currentContext, lifecycle, callback, "WifiRepository")
+ .apply {
+ // By default, [WifiPickerTracker] will scan to see all
+ // available wifi networks in the area. Because SysUI only
+ // needs to display the **connected** network, we don't
+ // need scans to be running (and in fact, running scans is
+ // costly and should be avoided whenever possible).
+ this?.disableScanning()
+ }
+
+ // The lifecycle must be STARTED in order for the callback to receive
+ // events.
+ mainExecutor.execute {
+ lifecycle.currentState = Lifecycle.State.STARTED
+ }
+ awaitClose {
+ mainExecutor.execute {
+ lifecycle.currentState = Lifecycle.State.CREATED
+ }
+ }
}
- }
+ .stateIn(scope, SharingStarted.Eagerly, current)
+ }
+ .stateIn(scope, SharingStarted.Eagerly, current)
+ } else {
- wifiPickerTracker =
- wifiPickerTrackerFactory.create(lifecycle, callback, "WifiRepository").apply {
- // By default, [WifiPickerTracker] will scan to see all available wifi
- // networks in the area. Because SysUI only needs to display the
- // **connected** network, we don't need scans to be running (and in fact,
- // running scans is costly and should be avoided whenever possible).
- this?.disableScanning()
+ run {
+ var current =
+ WifiPickerTrackerInfo(
+ state = WIFI_STATE_DEFAULT,
+ isDefault = false,
+ primaryNetwork = WIFI_NETWORK_DEFAULT,
+ secondaryNetworks = emptyList(),
+ )
+ callbackFlow {
+ val callback =
+ object : WifiPickerTracker.WifiPickerTrackerCallback {
+ override fun onWifiEntriesChanged() {
+ val connectedEntry = wifiPickerTracker.mergedOrPrimaryConnection
+ logOnWifiEntriesChanged(connectedEntry)
+
+ val activeNetworks =
+ wifiPickerTracker?.activeWifiEntries ?: emptyList()
+ val secondaryNetworks =
+ activeNetworks
+ .filter { it != connectedEntry && !it.isPrimaryNetwork }
+ .map { it.toWifiNetworkModel() }
+
+ // [WifiPickerTracker.connectedWifiEntry] will return the same
+ // instance
+ // but with updated internals. For example, when its validation
+ // status
+ // changes from false to true, the same instance is re-used but
+ // with the
+ // validated field updated.
+ //
+ // Because it's the same instance, the flow won't re-emit the
+ // value
+ // (even though the internals have changed). So, we need to
+ // transform it
+ // into our internal model immediately. [toWifiNetworkModel]
+ // always
+ // returns a new instance, so the flow is guaranteed to emit.
+ send(
+ newPrimaryNetwork =
+ connectedEntry?.toPrimaryWifiNetworkModel()
+ ?: WIFI_NETWORK_DEFAULT,
+ newSecondaryNetworks = secondaryNetworks,
+ newIsDefault = connectedEntry?.isDefaultNetwork ?: false,
+ )
+ }
+
+ override fun onWifiStateChanged() {
+ val state = wifiPickerTracker?.wifiState
+ logOnWifiStateChanged(state)
+ send(newState = state ?: WIFI_STATE_DEFAULT)
+ }
+
+ override fun onNumSavedNetworksChanged() {}
+
+ override fun onNumSavedSubscriptionsChanged() {}
+
+ private fun send(
+ newState: Int = current.state,
+ newIsDefault: Boolean = current.isDefault,
+ newPrimaryNetwork: WifiNetworkModel = current.primaryNetwork,
+ newSecondaryNetworks: List<WifiNetworkModel> =
+ current.secondaryNetworks,
+ ) {
+ val new =
+ WifiPickerTrackerInfo(
+ newState,
+ newIsDefault,
+ newPrimaryNetwork,
+ newSecondaryNetworks,
+ )
+ current = new
+ trySend(new)
+ }
+ }
+
+ wifiPickerTracker =
+ wifiPickerTrackerFactory
+ .create(applicationContext, lifecycle, callback, "WifiRepository")
+ .apply {
+ // By default, [WifiPickerTracker] will scan to see all
+ // available wifi
+ // networks in the area. Because SysUI only needs to display the
+ // **connected** network, we don't need scans to be running (and
+ // in fact,
+ // running scans is costly and should be avoided whenever
+ // possible).
+ this?.disableScanning()
+ }
+ // The lifecycle must be STARTED in order for the callback to receive
+ // events.
+ mainExecutor.execute { lifecycle.currentState = Lifecycle.State.STARTED }
+ awaitClose {
+ mainExecutor.execute {
+ lifecycle.currentState = Lifecycle.State.CREATED
+ }
+ }
}
- // The lifecycle must be STARTED in order for the callback to receive events.
- mainExecutor.execute { lifecycle.currentState = Lifecycle.State.STARTED }
- awaitClose {
- mainExecutor.execute { lifecycle.currentState = Lifecycle.State.CREATED }
- }
+ .stateIn(scope, SharingStarted.Eagerly, current)
}
- .stateIn(scope, SharingStarted.Eagerly, current)
- }
+ }
override val isWifiEnabled: StateFlow<Boolean> =
wifiPickerTrackerInfo
@@ -185,11 +329,7 @@ constructor(
wifiPickerTrackerInfo
.map { it.primaryNetwork }
.distinctUntilChanged()
- .logDiffsForTable(
- tableLogger,
- columnPrefix = "",
- initialValue = WIFI_NETWORK_DEFAULT,
- )
+ .logDiffsForTable(tableLogger, columnPrefix = "", initialValue = WIFI_NETWORK_DEFAULT)
.stateIn(scope, SharingStarted.Eagerly, WIFI_NETWORK_DEFAULT)
override val secondaryNetworks: StateFlow<List<WifiNetworkModel>> =
@@ -348,7 +488,7 @@ constructor(
TAG,
LogLevel.DEBUG,
{ str1 = prettyPrintActivity(activity) },
- { "onActivityChanged: $str1" }
+ { "onActivityChanged: $str1" },
)
}
@@ -379,13 +519,15 @@ constructor(
/** The currently primary wifi network. */
val primaryNetwork: WifiNetworkModel,
/** The current secondary network(s), if any. Specifically excludes the primary network. */
- val secondaryNetworks: List<WifiNetworkModel>
+ val secondaryNetworks: List<WifiNetworkModel>,
)
@SysUISingleton
class Factory
@Inject
constructor(
+ @Application private val applicationContext: Context,
+ private val userRepository: UserRepository,
@Application private val scope: CoroutineScope,
@Main private val mainExecutor: Executor,
@Background private val bgDispatcher: CoroutineDispatcher,
@@ -395,6 +537,8 @@ constructor(
) {
fun create(wifiManager: WifiManager): WifiRepositoryImpl {
return WifiRepositoryImpl(
+ applicationContext,
+ userRepository,
scope,
mainExecutor,
bgDispatcher,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/StatusBarPolicyModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/StatusBarPolicyModule.java
index c7bd5a1bb9a8..9187e3c43380 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/StatusBarPolicyModule.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/StatusBarPolicyModule.java
@@ -206,12 +206,14 @@ public interface StatusBarPolicyModule {
@SysUISingleton
@Provides
static AccessPointControllerImpl provideAccessPointControllerImpl(
+ @Application Context context,
UserManager userManager,
UserTracker userTracker,
@Main Executor mainExecutor,
WifiPickerTrackerFactory wifiPickerTrackerFactory
) {
AccessPointControllerImpl controller = new AccessPointControllerImpl(
+ context,
userManager,
userTracker,
mainExecutor,
diff --git a/packages/SystemUI/src/com/android/systemui/user/data/repository/UserRepository.kt b/packages/SystemUI/src/com/android/systemui/user/data/repository/UserRepository.kt
index e9a33e062c60..ad97b21ea60b 100644
--- a/packages/SystemUI/src/com/android/systemui/user/data/repository/UserRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/user/data/repository/UserRepository.kt
@@ -348,42 +348,53 @@ constructor(
private suspend fun getSettings(): UserSwitcherSettingsModel {
return withContext(backgroundDispatcher) {
- val isSimpleUserSwitcher =
- globalSettings.getInt(
- SETTING_SIMPLE_USER_SWITCHER,
- if (
- appContext.resources.getBoolean(
- com.android.internal.R.bool.config_expandLockScreenUserSwitcher
- )
- ) {
- 1
- } else {
- 0
- },
- ) != 0
-
- val isAddUsersFromLockscreen =
- globalSettings.getInt(Settings.Global.ADD_USERS_WHEN_LOCKED, 0) != 0
-
- val isUserSwitcherEnabled =
- globalSettings.getInt(
- Settings.Global.USER_SWITCHER_ENABLED,
- if (
- appContext.resources.getBoolean(
- com.android.internal.R.bool.config_showUserSwitcherByDefault
- )
- ) {
- 1
- } else {
- 0
- },
- ) != 0
-
- UserSwitcherSettingsModel(
- isSimpleUserSwitcher = isSimpleUserSwitcher,
- isAddUsersFromLockscreen = isAddUsersFromLockscreen,
- isUserSwitcherEnabled = isUserSwitcherEnabled,
- )
+ if (
+ // TODO(b/378068979): remove once login screen-specific logic
+ // is implemented at framework level.
+ appContext.resources.getBoolean(R.bool.config_userSwitchingMustGoThroughLoginScreen)
+ ) {
+ UserSwitcherSettingsModel(
+ isSimpleUserSwitcher = false,
+ isAddUsersFromLockscreen = false,
+ isUserSwitcherEnabled = false,
+ )
+ } else {
+ val isSimpleUserSwitcher =
+ globalSettings.getInt(
+ SETTING_SIMPLE_USER_SWITCHER,
+ if (
+ appContext.resources.getBoolean(
+ com.android.internal.R.bool.config_expandLockScreenUserSwitcher
+ )
+ ) {
+ 1
+ } else {
+ 0
+ },
+ ) != 0
+
+ val isAddUsersFromLockscreen =
+ globalSettings.getInt(Settings.Global.ADD_USERS_WHEN_LOCKED, 0) != 0
+
+ val isUserSwitcherEnabled =
+ globalSettings.getInt(
+ Settings.Global.USER_SWITCHER_ENABLED,
+ if (
+ appContext.resources.getBoolean(
+ com.android.internal.R.bool.config_showUserSwitcherByDefault
+ )
+ ) {
+ 1
+ } else {
+ 0
+ },
+ ) != 0
+ UserSwitcherSettingsModel(
+ isSimpleUserSwitcher = isSimpleUserSwitcher,
+ isAddUsersFromLockscreen = isAddUsersFromLockscreen,
+ isUserSwitcherEnabled = isUserSwitcherEnabled,
+ )
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/user/data/repository/UserSwitcherRepository.kt b/packages/SystemUI/src/com/android/systemui/user/data/repository/UserSwitcherRepository.kt
index a7983605eac9..bcbd679b35eb 100644
--- a/packages/SystemUI/src/com/android/systemui/user/data/repository/UserSwitcherRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/user/data/repository/UserSwitcherRepository.kt
@@ -21,6 +21,7 @@ import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.UserManager
import android.provider.Settings.Global.USER_SWITCHER_ENABLED
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.common.coroutine.ChannelExt.trySendWithFailureLogging
import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
import com.android.systemui.dagger.SysUISingleton
@@ -40,7 +41,6 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
-import com.android.app.tracing.coroutines.launchTraced as launch
import kotlinx.coroutines.withContext
interface UserSwitcherRepository {
@@ -67,6 +67,9 @@ constructor(
private val showUserSwitcherForSingleUser =
context.resources.getBoolean(R.bool.qs_show_user_switcher_for_single_user)
+ private val userSwitchingMustGoThroughLoginScreen =
+ context.resources.getBoolean(R.bool.config_userSwitchingMustGoThroughLoginScreen)
+
override val isEnabled: Flow<Boolean> = conflatedCallbackFlow {
suspend fun updateState() {
trySendWithFailureLogging(isUserSwitcherEnabled(), TAG)
@@ -135,7 +138,13 @@ constructor(
private suspend fun isUserSwitcherEnabled(): Boolean {
return withContext(bgDispatcher) {
- userManager.isUserSwitcherEnabled(showUserSwitcherForSingleUser)
+ // TODO(b/378068979): remove once login screen-specific logic
+ // is implemented at framework level.
+ if (userSwitchingMustGoThroughLoginScreen) {
+ false
+ } else {
+ userManager.isUserSwitcherEnabled(showUserSwitcherForSingleUser)
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletScreenController.java b/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletScreenController.java
index 53e6b4f82b7e..761993b3cda7 100644
--- a/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletScreenController.java
+++ b/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletScreenController.java
@@ -330,13 +330,19 @@ public class WalletScreenController implements
QAWalletCardViewInfo(Context context, WalletCard walletCard) {
mWalletCard = walletCard;
Icon cardImageIcon = mWalletCard.getCardImage();
- if (cardImageIcon.getType() == Icon.TYPE_URI) {
- mCardDrawable = null;
- } else {
+ if (cardImageIcon.getType() == Icon.TYPE_BITMAP
+ || cardImageIcon.getType() == Icon.TYPE_ADAPTIVE_BITMAP) {
mCardDrawable = mWalletCard.getCardImage().loadDrawable(context);
+ } else {
+ mCardDrawable = null;
}
Icon icon = mWalletCard.getCardIcon();
- mIconDrawable = icon == null ? null : icon.loadDrawable(context);
+ if (icon != null && (icon.getType() == Icon.TYPE_BITMAP
+ || icon.getType() == Icon.TYPE_ADAPTIVE_BITMAP)) {
+ mIconDrawable = icon.loadDrawable(context);
+ } else {
+ mIconDrawable = null;
+ }
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletView.java b/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletView.java
index 1a399341f12c..ca9b866e2d18 100644
--- a/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletView.java
+++ b/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletView.java
@@ -283,6 +283,11 @@ public class WalletView extends FrameLayout implements WalletCardCarousel.OnCard
return mCardLabel;
}
+ @VisibleForTesting
+ ImageView getIcon() {
+ return mIcon;
+ }
+
@Nullable
private static Drawable getHeaderIcon(Context context, WalletCardViewInfo walletCard) {
Drawable icon = walletCard.getIcon();
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
index 2b167e4c5da4..65b62737b692 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/keyguard/ClockEventControllerTest.kt
@@ -56,6 +56,7 @@ import com.android.systemui.plugins.clocks.ThemeConfig
import com.android.systemui.plugins.clocks.ZenData
import com.android.systemui.plugins.clocks.ZenData.ZenMode
import com.android.systemui.res.R
+import com.android.systemui.settings.UserTracker
import com.android.systemui.statusbar.policy.BatteryController
import com.android.systemui.statusbar.policy.ConfigurationController
import com.android.systemui.statusbar.policy.ZenModeController
@@ -128,6 +129,7 @@ class ClockEventControllerTest : SysuiTestCase() {
@Mock private lateinit var largeClockEvents: ClockFaceEvents
@Mock private lateinit var parentView: View
@Mock private lateinit var keyguardTransitionInteractor: KeyguardTransitionInteractor
+ @Mock private lateinit var userTracker: UserTracker
@Mock private lateinit var zenModeController: ZenModeController
private var zenModeControllerCallback: ZenModeController.Callback? = null
@@ -153,6 +155,7 @@ class ClockEventControllerTest : SysuiTestCase() {
.thenReturn(ClockFaceConfig(tickRate = ClockTickRate.PER_MINUTE))
whenever(smallClockController.theme).thenReturn(ThemeConfig(true, null))
whenever(largeClockController.theme).thenReturn(ThemeConfig(true, null))
+ whenever(userTracker.userId).thenReturn(1)
zenModeRepository.addMode(MANUAL_DND_INACTIVE)
@@ -177,6 +180,7 @@ class ClockEventControllerTest : SysuiTestCase() {
withDeps.featureFlags,
zenModeController,
kosmos.zenModeInteractor,
+ userTracker,
)
underTest.clock = clock
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/LegacyMediaDataManagerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/LegacyMediaDataManagerImplTest.kt
index fb376ce3ca40..3ddd4b58211d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/LegacyMediaDataManagerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/LegacyMediaDataManagerImplTest.kt
@@ -289,6 +289,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
}
verify(smartspaceManager).createSmartspaceSession(capture(smartSpaceConfigBuilderCaptor))
mediaControllerFactory.setControllerForToken(session.sessionToken, controller)
+ whenever(controller.sessionToken).thenReturn(session.sessionToken)
whenever(controller.transportControls).thenReturn(transportControls)
whenever(controller.playbackInfo).thenReturn(playbackInfo)
whenever(controller.metadata).thenReturn(metadataBuilder.build())
@@ -1599,6 +1600,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
verify(logger, never()).logResumeMediaAdded(anyInt(), eq(PACKAGE_NAME), any())
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testTooManyCompactActions_isTruncated() {
// GIVEN a notification where too many compact actions were specified
@@ -1635,6 +1637,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
.isEqualTo(LegacyMediaDataManagerImpl.MAX_COMPACT_ACTIONS)
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testTooManyNotificationActions_isTruncated() {
// GIVEN a notification where too many notification actions are added
@@ -1670,6 +1673,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
.isEqualTo(LegacyMediaDataManagerImpl.MAX_NOTIFICATION_ACTIONS)
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_noState_usesNotification() {
val desc = "Notification Action"
@@ -1703,6 +1707,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
assertThat(mediaDataCaptor.value!!.actions[0]!!.contentDescription).isEqualTo(desc)
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_hasPrevNext() {
val customDesc = arrayOf("custom 1", "custom 2", "custom 3", "custom 4")
@@ -1746,6 +1751,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
assertThat(actions.custom1!!.contentDescription).isEqualTo(customDesc[1])
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_noPrevNext_usesCustom() {
val customDesc = arrayOf("custom 1", "custom 2", "custom 3", "custom 4", "custom 5")
@@ -1778,6 +1784,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
assertThat(actions.custom1!!.contentDescription).isEqualTo(customDesc[3])
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_connecting() {
val stateActions = PlaybackState.ACTION_PLAY
@@ -1797,6 +1804,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
.isEqualTo(context.getString(R.string.controls_media_button_connecting))
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_reservedSpace() {
val customDesc = arrayOf("custom 1", "custom 2", "custom 3", "custom 4")
@@ -1835,6 +1843,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
assertThat(actions.reservePrev).isTrue()
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_playPause_hasButton() {
val stateActions = PlaybackState.ACTION_PLAY_PAUSE
@@ -1998,6 +2007,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
assertThat(mediaDataCaptor.value.semanticActions).isNotNull()
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackStateNull_Pause_keyExists_callsListener() {
whenever(controller.playbackState).thenReturn(null)
@@ -2056,6 +2066,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
assertThat(mediaDataCaptor.value.isClearable).isFalse()
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testRetain_notifPlayer_notifRemoved_setToResume() {
fakeFeatureFlags.set(MEDIA_RETAIN_SESSIONS, true)
@@ -2086,6 +2097,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
)
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testRetain_notifPlayer_sessionDestroyed_doesNotChange() {
fakeFeatureFlags.set(MEDIA_RETAIN_SESSIONS, true)
@@ -2104,6 +2116,7 @@ class LegacyMediaDataManagerImplTest(flags: FlagsParameterization) : SysuiTestCa
.onMediaDataLoaded(eq(PACKAGE_NAME), any(), any(), anyBoolean(), anyInt(), anyBoolean())
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testRetain_notifPlayer_removeWhileActive_fullyRemoved() {
fakeFeatureFlags.set(MEDIA_RETAIN_SESSIONS, true)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/MediaDataProcessorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/MediaDataProcessorTest.kt
index 7d364bd832f2..e5483c0980c0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/MediaDataProcessorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/controls/domain/pipeline/MediaDataProcessorTest.kt
@@ -103,7 +103,6 @@ import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Captor
import org.mockito.Mock
import org.mockito.Mockito
-import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.reset
import org.mockito.Mockito.verify
@@ -113,6 +112,7 @@ import org.mockito.junit.MockitoJUnit
import org.mockito.kotlin.any
import org.mockito.kotlin.capture
import org.mockito.kotlin.eq
+import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.mockito.quality.Strictness
import platform.test.runner.parameterized.ParameterizedAndroidJunit4
@@ -312,6 +312,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
}
verify(smartspaceManager).createSmartspaceSession(capture(smartSpaceConfigBuilderCaptor))
mediaControllerFactory.setControllerForToken(session.sessionToken, controller)
+ whenever(controller.sessionToken).thenReturn(session.sessionToken)
whenever(controller.transportControls).thenReturn(transportControls)
whenever(controller.playbackInfo).thenReturn(playbackInfo)
whenever(controller.metadata).thenReturn(metadataBuilder.build())
@@ -596,7 +597,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
fun testOnNotificationAdded_emptyTitle_hasPlaceholder() {
// When the manager has a notification with an empty title, and the app is not
// required to include a non-empty title
- val mockPackageManager = mock(PackageManager::class.java)
+ val mockPackageManager = mock<PackageManager>()
context.setMockPackageManager(mockPackageManager)
whenever(mockPackageManager.getApplicationLabel(any())).thenReturn(APP_NAME)
whenever(controller.metadata)
@@ -626,7 +627,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
fun testOnNotificationAdded_blankTitle_hasPlaceholder() {
// GIVEN that the manager has a notification with a blank title, and the app is not
// required to include a non-empty title
- val mockPackageManager = mock(PackageManager::class.java)
+ val mockPackageManager = mock<PackageManager>()
context.setMockPackageManager(mockPackageManager)
whenever(mockPackageManager.getApplicationLabel(any())).thenReturn(APP_NAME)
whenever(controller.metadata)
@@ -656,7 +657,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
fun testOnNotificationAdded_emptyMetadata_usesNotificationTitle() {
// When the app sets the metadata title fields to empty strings, but does include a
// non-blank notification title
- val mockPackageManager = mock(PackageManager::class.java)
+ val mockPackageManager = mock<PackageManager>()
context.setMockPackageManager(mockPackageManager)
whenever(mockPackageManager.getApplicationLabel(any())).thenReturn(APP_NAME)
whenever(controller.metadata)
@@ -1610,6 +1611,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
verify(logger, never()).logResumeMediaAdded(anyInt(), eq(PACKAGE_NAME), any())
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testTooManyCompactActions_isTruncated() {
// GIVEN a notification where too many compact actions were specified
@@ -1646,6 +1648,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
.isEqualTo(MediaDataProcessor.MAX_COMPACT_ACTIONS)
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testTooManyNotificationActions_isTruncated() {
// GIVEN a notification where too many notification actions are added
@@ -1681,6 +1684,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
.isEqualTo(MediaDataProcessor.MAX_NOTIFICATION_ACTIONS)
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_noState_usesNotification() {
val desc = "Notification Action"
@@ -1714,6 +1718,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
assertThat(mediaDataCaptor.value!!.actions[0]!!.contentDescription).isEqualTo(desc)
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_hasPrevNext() {
val customDesc = arrayOf("custom 1", "custom 2", "custom 3", "custom 4")
@@ -1757,6 +1762,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
assertThat(actions.custom1!!.contentDescription).isEqualTo(customDesc[1])
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_noPrevNext_usesCustom() {
val customDesc = arrayOf("custom 1", "custom 2", "custom 3", "custom 4", "custom 5")
@@ -1789,6 +1795,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
assertThat(actions.custom1!!.contentDescription).isEqualTo(customDesc[3])
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_connecting() {
val stateActions = PlaybackState.ACTION_PLAY
@@ -1874,6 +1881,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
.isNotEqualTo(firstSemanticActions.prevOrCustom?.icon)
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_reservedSpace() {
val customDesc = arrayOf("custom 1", "custom 2", "custom 3", "custom 4")
@@ -1912,6 +1920,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
assertThat(actions.reservePrev).isTrue()
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackActions_playPause_hasButton() {
val stateActions = PlaybackState.ACTION_PLAY_PAUSE
@@ -2074,6 +2083,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
assertThat(mediaDataCaptor.value.semanticActions).isNotNull()
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testPlaybackStateNull_Pause_keyExists_callsListener() {
whenever(controller.playbackState).thenReturn(null)
@@ -2132,6 +2142,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
assertThat(mediaDataCaptor.value.isClearable).isFalse()
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testRetain_notifPlayer_notifRemoved_setToResume() {
fakeFeatureFlags.set(MEDIA_RETAIN_SESSIONS, true)
@@ -2162,6 +2173,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
)
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testRetain_notifPlayer_sessionDestroyed_doesNotChange() {
fakeFeatureFlags.set(MEDIA_RETAIN_SESSIONS, true)
@@ -2180,6 +2192,7 @@ class MediaDataProcessorTest(flags: FlagsParameterization) : SysuiTestCase() {
.onMediaDataLoaded(eq(PACKAGE_NAME), any(), any(), anyBoolean(), anyInt(), anyBoolean())
}
+ @DisableFlags(Flags.FLAG_MEDIA_CONTROLS_BUTTON_MEDIA3)
@Test
fun testRetain_notifPlayer_removeWhileActive_fullyRemoved() {
fakeFeatureFlags.set(MEDIA_RETAIN_SESSIONS, true)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt
index c48898aad087..2e0b7c69f092 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt
@@ -67,12 +67,12 @@ import com.android.systemui.statusbar.pipeline.shared.data.repository.Connectivi
import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository
import com.android.systemui.statusbar.pipeline.wifi.data.repository.prod.WifiRepositoryImpl
import com.android.systemui.testKosmos
+import com.android.systemui.user.data.repository.fakeUserRepository
+import com.android.systemui.user.data.repository.userRepository
import com.android.systemui.util.concurrency.FakeExecutor
-import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.argumentCaptor
import com.android.systemui.util.mockito.capture
import com.android.systemui.util.mockito.eq
-import com.android.systemui.util.mockito.mock
import com.android.systemui.util.time.FakeSystemClock
import com.android.wifitrackerlib.MergedCarrierEntry
import com.android.wifitrackerlib.WifiEntry
@@ -96,6 +96,8 @@ import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
+import org.mockito.kotlin.any
+import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
@Suppress("EXPERIMENTAL_IS_NOT_ENABLED")
@@ -137,6 +139,7 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() {
private val wifiPickerTrackerCallback =
argumentCaptor<WifiPickerTracker.WifiPickerTrackerCallback>()
private val vcnTransportInfo = VcnTransportInfo.Builder().build()
+ private val userRepository = kosmos.fakeUserRepository
private val testDispatcher = StandardTestDispatcher()
private val testScope = TestScope(testDispatcher)
@@ -159,7 +162,14 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() {
logcatTableLogBuffer(kosmos, "test")
}
- whenever(wifiPickerTrackerFactory.create(any(), capture(wifiPickerTrackerCallback), any()))
+ whenever(
+ wifiPickerTrackerFactory.create(
+ any(),
+ any(),
+ capture(wifiPickerTrackerCallback),
+ any(),
+ )
+ )
.thenReturn(wifiPickerTracker)
// For convenience, set up the subscription info callbacks
@@ -188,6 +198,8 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() {
wifiRepository =
WifiRepositoryImpl(
+ mContext,
+ userRepository,
testScope.backgroundScope,
mainExecutor,
testDispatcher,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt
index 44e1437b909e..d823bf57c824 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/prod/WifiRepositoryImplTest.kt
@@ -16,13 +16,19 @@
package com.android.systemui.statusbar.pipeline.wifi.data.repository.prod
+import android.content.Context
+import android.content.pm.UserInfo
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.net.wifi.WifiManager.UNKNOWN_SSID
import android.net.wifi.sharedconnectivity.app.NetworkProviderInfo
+import android.os.UserHandle
+import android.platform.test.annotations.DisableFlags
+import android.platform.test.annotations.EnableFlags
import android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID
import android.testing.TestableLooper
import androidx.test.filters.SmallTest
+import com.android.systemui.Flags.FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT
import com.android.systemui.SysuiTestCase
import com.android.systemui.coroutines.collectLastValue
import com.android.systemui.log.LogBuffer
@@ -33,12 +39,10 @@ import com.android.systemui.statusbar.pipeline.wifi.data.repository.prod.WifiRep
import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel
import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiScanEntry
import com.android.systemui.testKosmos
+import com.android.systemui.user.data.repository.fakeUserRepository
+import com.android.systemui.user.data.repository.userRepository
import com.android.systemui.util.concurrency.FakeExecutor
-import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.argumentCaptor
-import com.android.systemui.util.mockito.capture
-import com.android.systemui.util.mockito.mock
-import com.android.systemui.util.mockito.whenever
import com.android.systemui.util.time.fakeSystemClock
import com.android.wifitrackerlib.HotspotNetworkEntry
import com.android.wifitrackerlib.HotspotNetworkEntry.DeviceType
@@ -56,7 +60,12 @@ import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
-import org.mockito.Mockito.verify
+import org.mockito.kotlin.any
+import org.mockito.kotlin.capture
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.times
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
/**
* Note: Most of these tests are duplicates of [WifiRepositoryImplTest] tests.
@@ -67,8 +76,9 @@ import org.mockito.Mockito.verify
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@TestableLooper.RunWithLooper(setAsMainLooper = true)
-class WifiRepositoryImplTest : SysuiTestCase() {
+class WifiRepositoryImplTest() : SysuiTestCase() {
private val kosmos = testKosmos()
+ private val userRepository = kosmos.fakeUserRepository
// Using lazy means that the class will only be constructed once it's fetched. Because the
// repository internally sets some values on construction, we need to set up some test
@@ -76,6 +86,8 @@ class WifiRepositoryImplTest : SysuiTestCase() {
// inside each test case without needing to manually recreate the repository.
private val underTest: WifiRepositoryImpl by lazy {
WifiRepositoryImpl(
+ mContext,
+ userRepository,
testScope.backgroundScope,
executor,
dispatcher,
@@ -101,7 +113,8 @@ class WifiRepositoryImplTest : SysuiTestCase() {
@Before
fun setUp() {
- whenever(wifiPickerTrackerFactory.create(any(), capture(callbackCaptor), any()))
+ userRepository.setUserInfos(listOf(PRIMARY_USER, ANOTHER_USER))
+ whenever(wifiPickerTrackerFactory.create(any(), any(), capture(callbackCaptor), any()))
.thenReturn(wifiPickerTracker)
}
@@ -1203,6 +1216,95 @@ class WifiRepositoryImplTest : SysuiTestCase() {
assertThat(latest).isEmpty()
}
+ // TODO(b/371586248): This test currently require currentUserContext to be public for testing,
+ // this needs to
+ // be updated to capture the argument instead so currentUserContext can be private.
+ @Test
+ @EnableFlags(FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT)
+ fun oneUserVerifyCreatingWifiPickerTracker_multiuserFlagEnabled() =
+ testScope.runTest {
+ val primaryUserMockContext = mock<Context>()
+ mContext.prepareCreateContextAsUser(
+ UserHandle.of(PRIMARY_USER_ID),
+ primaryUserMockContext,
+ )
+
+ userRepository.setSelectedUserInfo(PRIMARY_USER)
+ runCurrent()
+ val currentUserContext by collectLastValue(underTest.selectedUserContext)
+
+ assertThat(currentUserContext).isEqualTo(primaryUserMockContext)
+ verify(wifiPickerTrackerFactory).create(any(), any(), any(), any())
+ }
+
+ // TODO(b/371586248): This test currently require currentUserContext to be public for testing,
+ // this needs to
+ // be updated to capture the argument instead so currentUserContext can be private.
+ @Test
+ @EnableFlags(FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT)
+ fun changeUserVerifyCreatingWifiPickerTracker_multiuserEnabled() =
+ testScope.runTest {
+ val primaryUserMockContext = mock<Context>()
+ mContext.prepareCreateContextAsUser(
+ UserHandle.of(PRIMARY_USER_ID),
+ primaryUserMockContext,
+ )
+
+ runCurrent()
+ userRepository.setSelectedUserInfo(PRIMARY_USER)
+ runCurrent()
+ val currentUserContext by collectLastValue(underTest.selectedUserContext)
+
+ assertThat(currentUserContext).isEqualTo(primaryUserMockContext)
+
+ val otherUserMockContext = mock<Context>()
+ mContext.prepareCreateContextAsUser(
+ UserHandle.of(ANOTHER_USER_ID),
+ otherUserMockContext,
+ )
+
+ runCurrent()
+ userRepository.setSelectedUserInfo(ANOTHER_USER)
+ runCurrent()
+ val otherUserContext by collectLastValue(underTest.selectedUserContext)
+
+ assertThat(otherUserContext).isEqualTo(otherUserMockContext)
+ verify(wifiPickerTrackerFactory, times(2)).create(any(), any(), any(), any())
+ }
+
+ // TODO(b/371586248): This test currently require currentUserContext to be public for testing,
+ // this needs to
+ // be updated to capture the argument instead so currentUserContext can be private.
+ @Test
+ @DisableFlags(FLAG_MULTIUSER_WIFI_PICKER_TRACKER_SUPPORT)
+ fun changeUserVerifyCreatingWifiPickerTracker_multiuserDisabled() =
+ testScope.runTest {
+ val primaryUserMockContext = mock<Context>()
+ mContext.prepareCreateContextAsUser(
+ UserHandle.of(PRIMARY_USER_ID),
+ primaryUserMockContext,
+ )
+
+ runCurrent()
+ userRepository.setSelectedUserInfo(PRIMARY_USER)
+ runCurrent()
+ val currentUserContext by collectLastValue(underTest.selectedUserContext)
+
+ assertThat(currentUserContext).isEqualTo(primaryUserMockContext)
+
+ val otherUserMockContext = mock<Context>()
+ mContext.prepareCreateContextAsUser(
+ UserHandle.of(ANOTHER_USER_ID),
+ otherUserMockContext,
+ )
+
+ runCurrent()
+ userRepository.setSelectedUserInfo(ANOTHER_USER)
+ runCurrent()
+
+ verify(wifiPickerTrackerFactory, times(1)).create(any(), any(), any(), any())
+ }
+
private fun getCallback(): WifiPickerTracker.WifiPickerTrackerCallback {
testScope.runCurrent()
return callbackCaptor.value
@@ -1231,5 +1333,20 @@ class WifiRepositoryImplTest : SysuiTestCase() {
private companion object {
const val TITLE = "AB"
+ private const val PRIMARY_USER_ID = 0
+ private val PRIMARY_USER =
+ UserInfo(
+ /* id= */ PRIMARY_USER_ID,
+ /* name= */ "primary user",
+ /* flags= */ UserInfo.FLAG_PROFILE,
+ )
+
+ private const val ANOTHER_USER_ID = 1
+ private val ANOTHER_USER =
+ UserInfo(
+ /* id= */ ANOTHER_USER_ID,
+ /* name= */ "another user",
+ /* flags= */ UserInfo.FLAG_PROFILE,
+ )
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/wallet/ui/WalletScreenControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/wallet/ui/WalletScreenControllerTest.java
index 38a61fecdc8a..21adeb01487b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/wallet/ui/WalletScreenControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/wallet/ui/WalletScreenControllerTest.java
@@ -316,6 +316,31 @@ public class WalletScreenControllerTest extends SysuiTestCase {
}
@Test
+ public void queryCards_hasCards_showCarousel_invalidIconSource_noIcon() {
+ GetWalletCardsResponse response =
+ new GetWalletCardsResponse(
+ Collections.singletonList(createWalletCardWithInvalidIcon(mContext)), 0);
+
+ mController.queryWalletCards();
+ mTestableLooper.processAllMessages();
+
+ verify(mWalletClient).getWalletCards(any(), any(), mCallbackCaptor.capture());
+
+ QuickAccessWalletClient.OnWalletCardsRetrievedCallback callback =
+ mCallbackCaptor.getValue();
+
+ assertEquals(mController, callback);
+
+ callback.onWalletCardsRetrieved(response);
+ mTestableLooper.processAllMessages();
+
+ assertEquals(VISIBLE, mWalletView.getCardCarousel().getVisibility());
+ assertEquals(GONE, mWalletView.getEmptyStateView().getVisibility());
+ assertEquals(GONE, mWalletView.getErrorView().getVisibility());
+ assertEquals(null, mWalletView.getIcon().getDrawable());
+ }
+
+ @Test
public void queryCards_noCards_showEmptyState() {
GetWalletCardsResponse response = new GetWalletCardsResponse(Collections.EMPTY_LIST, 0);
@@ -507,6 +532,16 @@ public class WalletScreenControllerTest extends SysuiTestCase {
.build();
}
+ private WalletCard createWalletCardWithInvalidIcon(Context context) {
+ PendingIntent pendingIntent =
+ PendingIntent.getActivity(context, 0, mWalletIntent, PendingIntent.FLAG_IMMUTABLE);
+ return new WalletCard.Builder(
+ CARD_ID_1, createIconWithInvalidSource(), "•••• 1234", pendingIntent)
+ .setCardIcon(createIconWithInvalidSource())
+ .setCardLabel("Hold to reader")
+ .build();
+ }
+
private WalletCard createCrazyWalletCard(Context context, boolean hasLabel) {
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 0, mWalletIntent, PendingIntent.FLAG_IMMUTABLE);
@@ -520,6 +555,10 @@ public class WalletScreenControllerTest extends SysuiTestCase {
return Icon.createWithBitmap(Bitmap.createBitmap(70, 44, Bitmap.Config.ARGB_8888));
}
+ private static Icon createIconWithInvalidSource() {
+ return Icon.createWithContentUri("content://media/external/images/media");
+ }
+
private WalletCardViewInfo createCardViewInfo(WalletCard walletCard) {
return new WalletScreenController.QAWalletCardViewInfo(
mContext, walletCard);
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/authentication/data/repository/FakeAuthenticationRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/authentication/data/repository/FakeAuthenticationRepository.kt
index 219794f3ad18..a7917a0866bb 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/authentication/data/repository/FakeAuthenticationRepository.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/authentication/data/repository/FakeAuthenticationRepository.kt
@@ -37,9 +37,7 @@ import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.currentTime
-class FakeAuthenticationRepository(
- private val currentTime: () -> Long,
-) : AuthenticationRepository {
+class FakeAuthenticationRepository(private val currentTime: () -> Long) : AuthenticationRepository {
override val hintedPinLength: Int = HINTING_PIN_LENGTH
@@ -72,6 +70,9 @@ class FakeAuthenticationRepository(
private val credentialCheckingMutex = Mutex(locked = false)
+ var maximumTimeToLock: Long = 0
+ var powerButtonInstantlyLocks: Boolean = true
+
override suspend fun getAuthenticationMethod(): AuthenticationMethodModel {
return authenticationMethod.value
}
@@ -114,6 +115,7 @@ class FakeAuthenticationRepository(
MAX_FAILED_AUTH_TRIES_BEFORE_WIPE
var profileWithMinFailedUnlockAttemptsForWipe: Int = UserHandle.USER_SYSTEM
+
override suspend fun getProfileWithMinFailedUnlockAttemptsForWipe(): Int =
profileWithMinFailedUnlockAttemptsForWipe
@@ -144,10 +146,7 @@ class FakeAuthenticationRepository(
val failedAttempts = _failedAuthenticationAttempts.value
if (isSuccessful || failedAttempts < MAX_FAILED_AUTH_TRIES_BEFORE_LOCKOUT - 1) {
- AuthenticationResultModel(
- isSuccessful = isSuccessful,
- lockoutDurationMs = 0,
- )
+ AuthenticationResultModel(isSuccessful = isSuccessful, lockoutDurationMs = 0)
} else {
AuthenticationResultModel(
isSuccessful = false,
@@ -178,6 +177,14 @@ class FakeAuthenticationRepository(
credentialCheckingMutex.unlock()
}
+ override suspend fun getMaximumTimeToLock(): Long {
+ return maximumTimeToLock
+ }
+
+ override suspend fun getPowerButtonInstantlyLocks(): Boolean {
+ return powerButtonInstantlyLocks
+ }
+
private fun getExpectedCredential(securityMode: SecurityMode): List<Any> {
return when (val credentialType = getCurrentCredentialType(securityMode)) {
LockPatternUtils.CREDENTIAL_TYPE_PIN -> credentialOverride ?: DEFAULT_PIN
@@ -219,9 +226,7 @@ class FakeAuthenticationRepository(
}
@LockPatternUtils.CredentialType
- private fun getCurrentCredentialType(
- securityMode: SecurityMode,
- ): Int {
+ private fun getCurrentCredentialType(securityMode: SecurityMode): Int {
return when (securityMode) {
SecurityMode.PIN,
SecurityMode.SimPin,
@@ -260,9 +265,8 @@ class FakeAuthenticationRepository(
object FakeAuthenticationRepositoryModule {
@Provides
@SysUISingleton
- fun provideFake(
- scope: TestScope,
- ) = FakeAuthenticationRepository(currentTime = { scope.currentTime })
+ fun provideFake(scope: TestScope) =
+ FakeAuthenticationRepository(currentTime = { scope.currentTime })
@Module
interface Bindings {
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/repository/FakeDeviceEntryRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/repository/FakeDeviceEntryRepository.kt
index 2dcd275f0103..f6ff4c4a057e 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/repository/FakeDeviceEntryRepository.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/repository/FakeDeviceEntryRepository.kt
@@ -16,6 +16,7 @@
package com.android.systemui.deviceentry.data.repository
import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.deviceentry.shared.model.DeviceUnlockStatus
import dagger.Binds
import dagger.Module
import javax.inject.Inject
@@ -35,6 +36,9 @@ class FakeDeviceEntryRepository @Inject constructor() : DeviceEntryRepository {
private var pendingLockscreenEnabled = _isLockscreenEnabled.value
+ override val deviceUnlockStatus =
+ MutableStateFlow(DeviceUnlockStatus(isUnlocked = false, deviceUnlockSource = null))
+
override suspend fun isLockscreenEnabled(): Boolean {
_isLockscreenEnabled.value = pendingLockscreenEnabled
return isLockscreenEnabled.value
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorKosmos.kt
index 8922b2f5c5ef..b76fa356de33 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/domain/interactor/DeviceUnlockedInteractorKosmos.kt
@@ -19,25 +19,25 @@ package com.android.systemui.deviceentry.domain.interactor
import com.android.systemui.authentication.domain.interactor.authenticationInteractor
import com.android.systemui.deviceentry.data.repository.deviceEntryRepository
import com.android.systemui.flags.fakeSystemPropertiesHelper
-import com.android.systemui.flags.systemPropertiesHelper
-import com.android.systemui.keyguard.domain.interactor.keyguardTransitionInteractor
import com.android.systemui.keyguard.domain.interactor.trustInteractor
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.Kosmos.Fixture
-import com.android.systemui.kosmos.applicationCoroutineScope
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.lifecycle.activateIn
import com.android.systemui.power.domain.interactor.powerInteractor
+import com.android.systemui.util.settings.data.repository.userAwareSecureSettingsRepository
val Kosmos.deviceUnlockedInteractor by Fixture {
DeviceUnlockedInteractor(
- applicationScope = applicationCoroutineScope,
- authenticationInteractor = authenticationInteractor,
- deviceEntryRepository = deviceEntryRepository,
- trustInteractor = trustInteractor,
- faceAuthInteractor = deviceEntryFaceAuthInteractor,
- fingerprintAuthInteractor = deviceEntryFingerprintAuthInteractor,
- powerInteractor = powerInteractor,
- biometricSettingsInteractor = deviceEntryBiometricSettingsInteractor,
- systemPropertiesHelper = fakeSystemPropertiesHelper,
- keyguardTransitionInteractor = keyguardTransitionInteractor,
- )
+ authenticationInteractor = authenticationInteractor,
+ repository = deviceEntryRepository,
+ trustInteractor = trustInteractor,
+ faceAuthInteractor = deviceEntryFaceAuthInteractor,
+ fingerprintAuthInteractor = deviceEntryFingerprintAuthInteractor,
+ powerInteractor = powerInteractor,
+ biometricSettingsInteractor = deviceEntryBiometricSettingsInteractor,
+ systemPropertiesHelper = fakeSystemPropertiesHelper,
+ userAwareSecureSettingsRepository = userAwareSecureSettingsRepository,
+ )
+ .apply { activateIn(testScope) }
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryKosmos.kt
index f49e3771763a..b3be2c09c6f8 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/media/controls/domain/pipeline/Media3ActionFactoryKosmos.kt
@@ -22,6 +22,7 @@ import android.os.Handler
import android.os.looper
import androidx.media3.session.CommandButton
import androidx.media3.session.MediaController
+import androidx.media3.session.SessionCommand
import androidx.media3.session.SessionToken
import com.android.systemui.Flags
import com.android.systemui.graphics.imageLoader
@@ -30,7 +31,11 @@ import com.android.systemui.kosmos.testScope
import com.android.systemui.media.controls.shared.mediaLogger
import com.android.systemui.media.controls.util.fakeMediaControllerFactory
import com.android.systemui.media.controls.util.fakeSessionTokenFactory
+import com.android.systemui.util.concurrency.execution
import com.google.common.collect.ImmutableList
+import org.mockito.kotlin.any
+import org.mockito.kotlin.argumentCaptor
+import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
@@ -46,10 +51,22 @@ var Kosmos.media3ActionFactory: Media3ActionFactory by
mock<MediaController>().also {
whenever(it.customLayout).thenReturn(customLayout)
whenever(it.sessionExtras).thenReturn(Bundle())
+ whenever(it.isCommandAvailable(any())).thenReturn(true)
+ whenever(it.isSessionCommandAvailable(any<SessionCommand>())).thenReturn(true)
}
fakeMediaControllerFactory.setMedia3Controller(media3Controller)
fakeSessionTokenFactory.setMedia3SessionToken(mock<SessionToken>())
}
+
+ val runnableCaptor = argumentCaptor<Runnable>()
+ val handler =
+ mock<Handler> {
+ on { post(runnableCaptor.capture()) } doAnswer
+ {
+ runnableCaptor.lastValue.run()
+ true
+ }
+ }
Media3ActionFactory(
context = applicationContext,
imageLoader = imageLoader,
@@ -57,7 +74,8 @@ var Kosmos.media3ActionFactory: Media3ActionFactory by
tokenFactory = fakeSessionTokenFactory,
logger = mediaLogger,
looper = looper,
- handler = Handler(looper),
+ handler = handler,
bgScope = testScope,
+ execution = execution,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryKosmos.kt
index 513d4e418a41..1395b1818b30 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/panels/data/repository/QSPreferencesRepositoryKosmos.kt
@@ -16,8 +16,10 @@
package com.android.systemui.qs.panels.data.repository
+import com.android.systemui.broadcast.broadcastDispatcher
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.testDispatcher
+import com.android.systemui.log.core.FakeLogBuffer
import com.android.systemui.settings.userFileManager
import com.android.systemui.user.data.repository.userRepository
@@ -27,6 +29,8 @@ val Kosmos.qsPreferencesRepository by
userFileManager,
userRepository,
defaultLargeTilesRepository,
- testDispatcher
+ testDispatcher,
+ FakeLogBuffer.Factory.create(),
+ broadcastDispatcher,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt
index c3c3cce5cf68..dae66d42b2bc 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt
@@ -41,6 +41,7 @@ class FakeMobileConnectionRepository(
override val isGsm = MutableStateFlow(false)
override val cdmaLevel = MutableStateFlow(0)
override val primaryLevel = MutableStateFlow(0)
+ override val satelliteLevel = MutableStateFlow(0)
override val dataConnectionState = MutableStateFlow(DataConnectionState.Disconnected)
override val dataActivityDirection =
MutableStateFlow(DataActivityModel(hasActivityIn = false, hasActivityOut = false))
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityInputFilter.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityInputFilter.java
index 617cca9d3075..d6fc6e461edc 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityInputFilter.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityInputFilter.java
@@ -27,6 +27,8 @@ import android.annotation.NonNull;
import android.content.Context;
import android.graphics.Region;
import android.hardware.input.InputManager;
+import android.hardware.input.KeyGestureEvent;
+import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.os.SystemClock;
@@ -44,11 +46,14 @@ import android.view.MotionEvent.PointerCoords;
import android.view.MotionEvent.PointerProperties;
import android.view.accessibility.AccessibilityEvent;
+import androidx.annotation.Nullable;
+
import com.android.server.LocalServices;
import com.android.server.accessibility.gestures.TouchExplorer;
import com.android.server.accessibility.magnification.FullScreenMagnificationController;
import com.android.server.accessibility.magnification.FullScreenMagnificationGestureHandler;
import com.android.server.accessibility.magnification.FullScreenMagnificationVibrationHelper;
+import com.android.server.accessibility.magnification.MagnificationController;
import com.android.server.accessibility.magnification.MagnificationGestureHandler;
import com.android.server.accessibility.magnification.MouseEventHandler;
import com.android.server.accessibility.magnification.WindowMagnificationGestureHandler;
@@ -187,6 +192,8 @@ class AccessibilityInputFilter extends InputFilter implements EventStreamTransfo
private final AccessibilityManagerService mAms;
+ private final InputManager mInputManager;
+
private final SparseArray<EventStreamTransformation> mEventHandler;
private final SparseArray<TouchExplorer> mTouchExplorer = new SparseArray<>(0);
@@ -228,6 +235,47 @@ class AccessibilityInputFilter extends InputFilter implements EventStreamTransfo
*/
private MotionEvent mLastActiveDeviceMotionEvent = null;
+ private boolean mKeyGestureEventHandlerInstalled = false;
+ private InputManager.KeyGestureEventHandler mKeyGestureEventHandler =
+ new InputManager.KeyGestureEventHandler() {
+ @Override
+ public boolean handleKeyGestureEvent(
+ @NonNull KeyGestureEvent event,
+ @Nullable IBinder focusedToken) {
+ final boolean complete =
+ event.getAction() == KeyGestureEvent.ACTION_GESTURE_COMPLETE
+ && !event.isCancelled();
+ final int gestureType = event.getKeyGestureType();
+ final int displayId = isDisplayIdValid(event.getDisplayId())
+ ? event.getDisplayId() : Display.DEFAULT_DISPLAY;
+
+ switch (gestureType) {
+ case KeyGestureEvent.KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_IN:
+ if (complete) {
+ mAms.getMagnificationController().scaleMagnificationByStep(
+ displayId, MagnificationController.ZOOM_DIRECTION_IN);
+ }
+ return true;
+ case KeyGestureEvent.KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_OUT:
+ if (complete) {
+ mAms.getMagnificationController().scaleMagnificationByStep(
+ displayId, MagnificationController.ZOOM_DIRECTION_OUT);
+ }
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isKeyGestureSupported(int gestureType) {
+ return switch (gestureType) {
+ case KeyGestureEvent.KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_IN,
+ KeyGestureEvent.KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_OUT -> true;
+ default -> false;
+ };
+ }
+ };
+
private static MotionEvent cancelMotion(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_CANCEL
|| event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT
@@ -287,6 +335,7 @@ class AccessibilityInputFilter extends InputFilter implements EventStreamTransfo
mContext = context;
mAms = service;
mPm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
+ mInputManager = context.getSystemService(InputManager.class);
mEventHandler = eventHandler;
}
@@ -723,6 +772,12 @@ class AccessibilityInputFilter extends InputFilter implements EventStreamTransfo
createMagnificationGestureHandler(displayId, displayContext);
addFirstEventHandler(displayId, magnificationGestureHandler);
mMagnificationGestureHandler.put(displayId, magnificationGestureHandler);
+
+ if (com.android.hardware.input.Flags.enableTalkbackAndMagnifierKeyGestures()
+ && !mKeyGestureEventHandlerInstalled) {
+ mInputManager.registerKeyGestureEventHandler(mKeyGestureEventHandler);
+ mKeyGestureEventHandlerInstalled = true;
+ }
}
if ((mEnabledFeatures & FLAG_FEATURE_INJECT_MOTION_EVENTS) != 0) {
@@ -842,6 +897,11 @@ class AccessibilityInputFilter extends InputFilter implements EventStreamTransfo
mMouseKeysInterceptor.onDestroy();
mMouseKeysInterceptor = null;
}
+
+ if (mKeyGestureEventHandlerInstalled) {
+ mInputManager.unregisterKeyGestureEventHandler(mKeyGestureEventHandler);
+ mKeyGestureEventHandlerInstalled = false;
+ }
}
private MagnificationGestureHandler createMagnificationGestureHandler(
diff --git a/services/accessibility/java/com/android/server/accessibility/magnification/MagnificationController.java b/services/accessibility/java/com/android/server/accessibility/magnification/MagnificationController.java
index d40e7476f7ec..51c4305061f8 100644
--- a/services/accessibility/java/com/android/server/accessibility/magnification/MagnificationController.java
+++ b/services/accessibility/java/com/android/server/accessibility/magnification/MagnificationController.java
@@ -27,6 +27,7 @@ import static android.provider.Settings.Secure.ACCESSIBILITY_MAGNIFICATION_MODE_
import static com.android.server.accessibility.AccessibilityManagerService.MAGNIFICATION_GESTURE_HANDLER_ID;
import android.accessibilityservice.MagnificationConfig;
+import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
@@ -101,6 +102,7 @@ public class MagnificationController implements MagnificationConnectionManager.C
private int mMagnificationCapabilities = ACCESSIBILITY_MAGNIFICATION_MODE_FULLSCREEN;
/** Whether the platform supports window magnification feature. */
private final boolean mSupportWindowMagnification;
+ private final MagnificationScaleStepProvider mScaleStepProvider;
private final Executor mBackgroundExecutor;
@@ -131,6 +133,14 @@ public class MagnificationController implements MagnificationConnectionManager.C
.UiChangesForAccessibilityCallbacks> mAccessibilityCallbacksDelegateArray =
new SparseArray<>();
+ // Direction magnifier scale can be altered.
+ public static final int ZOOM_DIRECTION_IN = 0;
+ public static final int ZOOM_DIRECTION_OUT = 1;
+
+ @IntDef({ZOOM_DIRECTION_IN, ZOOM_DIRECTION_OUT})
+ public @interface ZoomDirection {
+ }
+
/**
* A callback to inform the magnification transition result on the given display.
*/
@@ -144,6 +154,41 @@ public class MagnificationController implements MagnificationConnectionManager.C
void onResult(int displayId, boolean success);
}
+
+ /**
+ * An interface to configure how much the magnification scale should be affected when moving in
+ * steps.
+ */
+ public interface MagnificationScaleStepProvider {
+ /**
+ * Calculate the next value given which direction (in/out) to adjust the magnification
+ * scale.
+ *
+ * @param currentScale The current magnification scale value.
+ * @param direction Whether to zoom in or out.
+ * @return The next scale value.
+ */
+ float nextScaleStep(float currentScale, @ZoomDirection int direction);
+ }
+
+ public static class DefaultMagnificationScaleStepProvider implements
+ MagnificationScaleStepProvider {
+ // Factor of magnification scale. For example, when this value is 1.189, scale
+ // value will be changed x1.000, x1.189, x1.414, x1.681, x2.000, ...
+ // Note: this value is 2.0 ^ (1 / 4).
+ public static final float ZOOM_STEP_SCALE_FACTOR = 1.18920712f;
+
+ @Override
+ public float nextScaleStep(float currentScale, @ZoomDirection int direction) {
+ final int stepDelta = direction == ZOOM_DIRECTION_IN ? 1 : -1;
+ final long scaleIndex = Math.round(
+ Math.log(currentScale) / Math.log(ZOOM_STEP_SCALE_FACTOR));
+ final float nextScale = (float) Math.pow(ZOOM_STEP_SCALE_FACTOR,
+ scaleIndex + stepDelta);
+ return MagnificationScaleProvider.constrainScale(nextScale);
+ }
+ }
+
public MagnificationController(AccessibilityManagerService ams, Object lock,
Context context, MagnificationScaleProvider scaleProvider,
Executor backgroundExecutor) {
@@ -156,6 +201,7 @@ public class MagnificationController implements MagnificationConnectionManager.C
.getAccessibilityController().setUiChangesForAccessibilityCallbacks(this);
mSupportWindowMagnification = context.getPackageManager().hasSystemFeature(
FEATURE_WINDOW_MAGNIFICATION);
+ mScaleStepProvider = new DefaultMagnificationScaleStepProvider();
mAlwaysOnMagnificationFeatureFlag = new AlwaysOnMagnificationFeatureFlag(context);
mAlwaysOnMagnificationFeatureFlag.addOnChangedListener(
@@ -891,6 +937,37 @@ public class MagnificationController implements MagnificationConnectionManager.C
return isActivated;
}
+ /**
+ * Scales the magnifier on the given display one step in/out based on the zoomIn param.
+ *
+ * @param displayId The logical display id.
+ * @param direction Whether the scale should be zoomed in or out.
+ * @return {@code true} if the magnification scale was affected.
+ */
+ public boolean scaleMagnificationByStep(int displayId, @ZoomDirection int direction) {
+ if (getFullScreenMagnificationController().isActivated(displayId)) {
+ final float magnificationScale = getFullScreenMagnificationController().getScale(
+ displayId);
+ final float nextMagnificationScale = mScaleStepProvider.nextScaleStep(
+ magnificationScale, direction);
+ getFullScreenMagnificationController().setScaleAndCenter(displayId,
+ nextMagnificationScale,
+ Float.NaN, Float.NaN, true, MAGNIFICATION_GESTURE_HANDLER_ID);
+ return nextMagnificationScale != magnificationScale;
+ }
+
+ if (getMagnificationConnectionManager().isWindowMagnifierEnabled(displayId)) {
+ final float magnificationScale = getMagnificationConnectionManager().getScale(
+ displayId);
+ final float nextMagnificationScale = mScaleStepProvider.nextScaleStep(
+ magnificationScale, direction);
+ getMagnificationConnectionManager().setScale(displayId, nextMagnificationScale);
+ return nextMagnificationScale != magnificationScale;
+ }
+
+ return false;
+ }
+
private final class DisableMagnificationCallback implements
MagnificationAnimationCallback {
private final TransitionCallBack mTransitionCallBack;
diff --git a/services/appfunctions/java/com/android/server/appfunctions/AppFunctionManagerServiceImpl.java b/services/appfunctions/java/com/android/server/appfunctions/AppFunctionManagerServiceImpl.java
index 268e56487c4b..f13e22950e2d 100644
--- a/services/appfunctions/java/com/android/server/appfunctions/AppFunctionManagerServiceImpl.java
+++ b/services/appfunctions/java/com/android/server/appfunctions/AppFunctionManagerServiceImpl.java
@@ -29,7 +29,7 @@ import android.app.appfunctions.AppFunctionManagerHelper;
import android.app.appfunctions.AppFunctionRuntimeMetadata;
import android.app.appfunctions.AppFunctionStaticMetadataHelper;
import android.app.appfunctions.ExecuteAppFunctionAidlRequest;
-import android.app.appfunctions.ExecuteAppFunctionResponse;
+import android.app.appfunctions.AppFunctionException;
import android.app.appfunctions.IAppFunctionEnabledCallback;
import android.app.appfunctions.IAppFunctionManager;
import android.app.appfunctions.IAppFunctionService;
@@ -156,11 +156,10 @@ public class AppFunctionManagerServiceImpl extends IAppFunctionManager.Stub {
mCallerValidator.verifyTargetUserHandle(
requestInternal.getUserHandle(), validatedCallingPackage);
} catch (SecurityException exception) {
- safeExecuteAppFunctionCallback.onResult(
- ExecuteAppFunctionResponse.newFailure(
- ExecuteAppFunctionResponse.RESULT_DENIED,
- exception.getMessage(),
- /* extras= */ null));
+ safeExecuteAppFunctionCallback.onError(
+ new AppFunctionException(
+ AppFunctionException.ERROR_DENIED,
+ exception.getMessage()));
return null;
}
@@ -180,7 +179,7 @@ public class AppFunctionManagerServiceImpl extends IAppFunctionManager.Stub {
safeExecuteAppFunctionCallback,
executeAppFunctionCallback.asBinder());
} catch (Exception e) {
- safeExecuteAppFunctionCallback.onResult(
+ safeExecuteAppFunctionCallback.onError(
mapExceptionToExecuteAppFunctionResponse(e));
}
});
@@ -198,22 +197,19 @@ public class AppFunctionManagerServiceImpl extends IAppFunctionManager.Stub {
UserHandle targetUser = requestInternal.getUserHandle();
// TODO(b/354956319): Add and honor the new enterprise policies.
if (mCallerValidator.isUserOrganizationManaged(targetUser)) {
- safeExecuteAppFunctionCallback.onResult(
- ExecuteAppFunctionResponse.newFailure(
- ExecuteAppFunctionResponse.RESULT_SYSTEM_ERROR,
+ safeExecuteAppFunctionCallback.onError(
+ new AppFunctionException(AppFunctionException.ERROR_SYSTEM_ERROR,
"Cannot run on a device with a device owner or from the managed"
- + " profile.",
- /* extras= */ null));
+ + " profile."));
return;
}
String targetPackageName = requestInternal.getClientRequest().getTargetPackageName();
if (TextUtils.isEmpty(targetPackageName)) {
- safeExecuteAppFunctionCallback.onResult(
- ExecuteAppFunctionResponse.newFailure(
- ExecuteAppFunctionResponse.RESULT_INVALID_ARGUMENT,
- "Target package name cannot be empty.",
- /* extras= */ null));
+ safeExecuteAppFunctionCallback.onError(
+ new AppFunctionException(
+ AppFunctionException.ERROR_INVALID_ARGUMENT,
+ "Target package name cannot be empty."));
return;
}
@@ -253,11 +249,10 @@ public class AppFunctionManagerServiceImpl extends IAppFunctionManager.Stub {
mInternalServiceHelper.resolveAppFunctionService(
targetPackageName, targetUser);
if (serviceIntent == null) {
- safeExecuteAppFunctionCallback.onResult(
- ExecuteAppFunctionResponse.newFailure(
- ExecuteAppFunctionResponse.RESULT_SYSTEM_ERROR,
- "Cannot find the target service.",
- /* extras= */ null));
+ safeExecuteAppFunctionCallback.onError(
+ new AppFunctionException(
+ AppFunctionException.ERROR_SYSTEM_ERROR,
+ "Cannot find the target service."));
return;
}
bindAppFunctionServiceUnchecked(
@@ -272,7 +267,7 @@ public class AppFunctionManagerServiceImpl extends IAppFunctionManager.Stub {
})
.exceptionally(
ex -> {
- safeExecuteAppFunctionCallback.onResult(
+ safeExecuteAppFunctionCallback.onError(
mapExceptionToExecuteAppFunctionResponse(ex));
return null;
});
@@ -446,11 +441,9 @@ public class AppFunctionManagerServiceImpl extends IAppFunctionManager.Stub {
if (!bindServiceResult) {
Slog.e(TAG, "Failed to bind to the AppFunctionService");
- safeExecuteAppFunctionCallback.onResult(
- ExecuteAppFunctionResponse.newFailure(
- ExecuteAppFunctionResponse.RESULT_SYSTEM_ERROR,
- "Failed to bind the AppFunctionService.",
- /* extras= */ null));
+ safeExecuteAppFunctionCallback.onError(
+ new AppFunctionException(AppFunctionException.ERROR_SYSTEM_ERROR,
+ "Failed to bind the AppFunctionService."));
}
}
@@ -459,22 +452,21 @@ public class AppFunctionManagerServiceImpl extends IAppFunctionManager.Stub {
.getSystemService(AppSearchManager.class);
}
- private ExecuteAppFunctionResponse mapExceptionToExecuteAppFunctionResponse(Throwable e) {
+ private AppFunctionException mapExceptionToExecuteAppFunctionResponse(Throwable e) {
if (e instanceof CompletionException) {
e = e.getCause();
}
- int resultCode = ExecuteAppFunctionResponse.RESULT_SYSTEM_ERROR;
+ int resultCode = AppFunctionException.ERROR_SYSTEM_ERROR;
if (e instanceof AppSearchException appSearchException) {
resultCode =
mapAppSearchResultFailureCodeToExecuteAppFunctionResponse(
appSearchException.getResultCode());
} else if (e instanceof SecurityException) {
- resultCode = ExecuteAppFunctionResponse.RESULT_DENIED;
+ resultCode = AppFunctionException.ERROR_DENIED;
} else if (e instanceof DisabledAppFunctionException) {
- resultCode = ExecuteAppFunctionResponse.RESULT_DISABLED;
+ resultCode = AppFunctionException.ERROR_DISABLED;
}
- return ExecuteAppFunctionResponse.newFailure(
- resultCode, e.getMessage(), /* extras= */ null);
+ return new AppFunctionException(resultCode, e.getMessage());
}
private int mapAppSearchResultFailureCodeToExecuteAppFunctionResponse(int resultCode) {
@@ -485,13 +477,13 @@ public class AppFunctionManagerServiceImpl extends IAppFunctionManager.Stub {
switch (resultCode) {
case AppSearchResult.RESULT_NOT_FOUND:
- return ExecuteAppFunctionResponse.RESULT_FUNCTION_NOT_FOUND;
+ return AppFunctionException.ERROR_FUNCTION_NOT_FOUND;
case AppSearchResult.RESULT_INVALID_ARGUMENT:
case AppSearchResult.RESULT_INTERNAL_ERROR:
case AppSearchResult.RESULT_SECURITY_ERROR:
// fall-through
}
- return ExecuteAppFunctionResponse.RESULT_SYSTEM_ERROR;
+ return AppFunctionException.ERROR_SYSTEM_ERROR;
}
private void registerAppSearchObserver(@NonNull TargetUser user) {
diff --git a/services/appfunctions/java/com/android/server/appfunctions/RunAppFunctionServiceCallback.java b/services/appfunctions/java/com/android/server/appfunctions/RunAppFunctionServiceCallback.java
index 129be65f3153..c689bb92f8f7 100644
--- a/services/appfunctions/java/com/android/server/appfunctions/RunAppFunctionServiceCallback.java
+++ b/services/appfunctions/java/com/android/server/appfunctions/RunAppFunctionServiceCallback.java
@@ -17,6 +17,7 @@ package com.android.server.appfunctions;
import android.annotation.NonNull;
import android.app.appfunctions.ExecuteAppFunctionAidlRequest;
+import android.app.appfunctions.AppFunctionException;
import android.app.appfunctions.ExecuteAppFunctionResponse;
import android.app.appfunctions.IAppFunctionService;
import android.app.appfunctions.ICancellationCallback;
@@ -57,17 +58,22 @@ public class RunAppFunctionServiceCallback implements RunServiceCallCallback<IAp
mCancellationCallback,
new IExecuteAppFunctionCallback.Stub() {
@Override
- public void onResult(ExecuteAppFunctionResponse response) {
+ public void onSuccess(ExecuteAppFunctionResponse response) {
mSafeExecuteAppFunctionCallback.onResult(response);
serviceUsageCompleteListener.onCompleted();
}
+
+ @Override
+ public void onError(AppFunctionException error) {
+ mSafeExecuteAppFunctionCallback.onError(error);
+ serviceUsageCompleteListener.onCompleted();
+ }
});
} catch (Exception e) {
- mSafeExecuteAppFunctionCallback.onResult(
- ExecuteAppFunctionResponse.newFailure(
- ExecuteAppFunctionResponse.RESULT_APP_UNKNOWN_ERROR,
- e.getMessage(),
- /* extras= */ null));
+ mSafeExecuteAppFunctionCallback.onError(
+ new AppFunctionException(
+ AppFunctionException.ERROR_APP_UNKNOWN_ERROR,
+ e.getMessage()));
serviceUsageCompleteListener.onCompleted();
}
}
@@ -75,11 +81,9 @@ public class RunAppFunctionServiceCallback implements RunServiceCallCallback<IAp
@Override
public void onFailedToConnect() {
Slog.e(TAG, "Failed to connect to service");
- mSafeExecuteAppFunctionCallback.onResult(
- ExecuteAppFunctionResponse.newFailure(
- ExecuteAppFunctionResponse.RESULT_APP_UNKNOWN_ERROR,
- "Failed to connect to AppFunctionService",
- /* extras= */ null));
+ mSafeExecuteAppFunctionCallback.onError(
+ new AppFunctionException(AppFunctionException.ERROR_APP_UNKNOWN_ERROR,
+ "Failed to connect to AppFunctionService"));
}
@Override
diff --git a/services/backup/java/com/android/server/backup/UserBackupManagerService.java b/services/backup/java/com/android/server/backup/UserBackupManagerService.java
index ddccb3731cc1..466d477992b3 100644
--- a/services/backup/java/com/android/server/backup/UserBackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/UserBackupManagerService.java
@@ -281,6 +281,9 @@ public class UserBackupManagerService {
private static final int SCHEDULE_FILE_VERSION = 1;
public static final String SETTINGS_PACKAGE = "com.android.providers.settings";
+
+ public static final String TELEPHONY_PROVIDER_PACKAGE = "com.android.providers.telephony";
+
public static final String SHARED_BACKUP_AGENT_PACKAGE = "com.android.sharedstoragebackup";
// Pseudoname that we use for the Package Manager metadata "package".
diff --git a/services/backup/java/com/android/server/backup/utils/BackupEligibilityRules.java b/services/backup/java/com/android/server/backup/utils/BackupEligibilityRules.java
index f24a3c1afc86..508b62cd83f0 100644
--- a/services/backup/java/com/android/server/backup/utils/BackupEligibilityRules.java
+++ b/services/backup/java/com/android/server/backup/utils/BackupEligibilityRules.java
@@ -21,6 +21,7 @@ import static com.android.server.backup.BackupManagerService.TAG;
import static com.android.server.backup.UserBackupManagerService.PACKAGE_MANAGER_SENTINEL;
import static com.android.server.backup.UserBackupManagerService.SETTINGS_PACKAGE;
import static com.android.server.backup.UserBackupManagerService.SHARED_BACKUP_AGENT_PACKAGE;
+import static com.android.server.backup.UserBackupManagerService.TELEPHONY_PROVIDER_PACKAGE;
import static com.android.server.backup.UserBackupManagerService.WALLPAPER_PACKAGE;
import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
@@ -75,6 +76,12 @@ public class BackupEligibilityRules {
systemPackagesAllowedForProfileUser,
Sets.newArraySet(WALLPAPER_PACKAGE, SETTINGS_PACKAGE));
+ static {
+ if (UserManager.isHeadlessSystemUserMode()) {
+ systemPackagesAllowedForNonSystemUsers.add(TELEPHONY_PROVIDER_PACKAGE);
+ }
+ }
+
private final PackageManager mPackageManager;
private final PackageManagerInternal mPackageManagerInternal;
private final int mUserId;
diff --git a/services/core/Android.bp b/services/core/Android.bp
index 7f482ac79989..aea16b08df49 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -238,6 +238,7 @@ java_library_static {
"connectivity_flags_lib",
"device_config_service_flags_java",
"dreams_flags_lib",
+ "aconfig_flags_java",
"aconfig_new_storage_flags_lib",
"powerstats_flags_lib",
"locksettings_flags_lib",
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index 72a9a2d6de26..fa228627c255 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -88,6 +88,7 @@ import android.telephony.emergency.EmergencyNumber;
import android.telephony.ims.ImsCallSession;
import android.telephony.ims.ImsReasonInfo;
import android.telephony.ims.MediaQualityStatus;
+import android.telephony.satellite.NtnSignalStrength;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
@@ -440,6 +441,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
private boolean[] mCarrierRoamingNtnEligible = null;
private List<IntArray> mCarrierRoamingNtnAvailableServices;
+ private NtnSignalStrength[] mCarrierRoamingNtnSignalStrength;
// Local cache to check if Satellite Modem is enabled
private AtomicBoolean mIsSatelliteEnabled;
@@ -745,6 +747,12 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mSCBMDuration = copyOf(mSCBMDuration, mNumPhones);
mCarrierRoamingNtnMode = copyOf(mCarrierRoamingNtnMode, mNumPhones);
mCarrierRoamingNtnEligible = copyOf(mCarrierRoamingNtnEligible, mNumPhones);
+ if (mCarrierRoamingNtnSignalStrength != null) {
+ mCarrierRoamingNtnSignalStrength = copyOf(
+ mCarrierRoamingNtnSignalStrength, mNumPhones);
+ } else {
+ mCarrierRoamingNtnSignalStrength = new NtnSignalStrength[mNumPhones];
+ }
// ds -> ss switch.
if (mNumPhones < oldNumPhones) {
cutListToSize(mCellInfo, mNumPhones);
@@ -807,6 +815,8 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCarrierRoamingNtnMode[i] = false;
mCarrierRoamingNtnEligible[i] = false;
mCarrierRoamingNtnAvailableServices.add(i, new IntArray());
+ mCarrierRoamingNtnSignalStrength[i] = new NtnSignalStrength(
+ NtnSignalStrength.NTN_SIGNAL_STRENGTH_NONE);
}
}
}
@@ -883,6 +893,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCarrierRoamingNtnMode = new boolean[numPhones];
mCarrierRoamingNtnEligible = new boolean[numPhones];
mCarrierRoamingNtnAvailableServices = new ArrayList<>();
+ mCarrierRoamingNtnSignalStrength = new NtnSignalStrength[numPhones];
mIsSatelliteEnabled = new AtomicBoolean();
mWasSatelliteEnabledNotified = new AtomicBoolean();
@@ -932,6 +943,8 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCarrierRoamingNtnMode[i] = false;
mCarrierRoamingNtnEligible[i] = false;
mCarrierRoamingNtnAvailableServices.add(i, new IntArray());
+ mCarrierRoamingNtnSignalStrength[i] = new NtnSignalStrength(
+ NtnSignalStrength.NTN_SIGNAL_STRENGTH_NONE);
}
mAppOps = mContext.getSystemService(AppOpsManager.class);
@@ -1565,6 +1578,15 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
remove(r.binder);
}
}
+ if (events.contains(
+ TelephonyCallback.EVENT_CARRIER_ROAMING_NTN_SIGNAL_STRENGTH_CHANGED)) {
+ try {
+ r.callback.onCarrierRoamingNtnSignalStrengthChanged(
+ mCarrierRoamingNtnSignalStrength[r.phoneId]);
+ } catch (RemoteException ex) {
+ remove(r.binder);
+ }
+ }
}
}
}
@@ -3803,6 +3825,44 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
}
}
+
+ /**
+ * Notify external listeners that carrier roaming non-terrestrial network
+ * signal strength changed.
+ * @param subId subscription ID.
+ * @param ntnSignalStrength non-terrestrial network signal strength.
+ */
+ public void notifyCarrierRoamingNtnSignalStrengthChanged(int subId,
+ @NonNull NtnSignalStrength ntnSignalStrength) {
+ if (!checkNotifyPermission("notifyCarrierRoamingNtnSignalStrengthChanged")) {
+ log("nnotifyCarrierRoamingNtnSignalStrengthChanged: caller does not have required "
+ + "permissions.");
+ return;
+ }
+
+ if (VDBG) {
+ log("notifyCarrierRoamingNtnSignalStrengthChanged: "
+ + "subId=" + subId + " ntnSignalStrength=" + ntnSignalStrength.getLevel());
+ }
+
+ synchronized (mRecords) {
+ int phoneId = getPhoneIdFromSubId(subId);
+ mCarrierRoamingNtnSignalStrength[phoneId] = ntnSignalStrength;
+ for (Record r : mRecords) {
+ if (r.matchTelephonyCallbackEvent(
+ TelephonyCallback.EVENT_CARRIER_ROAMING_NTN_SIGNAL_STRENGTH_CHANGED)
+ && idMatch(r, subId, phoneId)) {
+ try {
+ r.callback.onCarrierRoamingNtnSignalStrengthChanged(ntnSignalStrength);
+ } catch (RemoteException ex) {
+ mRemoveList.add(r.binder);
+ }
+ }
+ }
+ handleRemoveListLocked();
+ }
+ }
+
@NeverCompile // Avoid size overhead of debugging code.
@Override
public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
@@ -3858,6 +3918,8 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
pw.println("mSCBMDuration=" + mSCBMDuration[i]);
pw.println("mCarrierRoamingNtnMode=" + mCarrierRoamingNtnMode[i]);
pw.println("mCarrierRoamingNtnEligible=" + mCarrierRoamingNtnEligible[i]);
+ pw.println("mCarrierRoamingNtnSignalStrength="
+ + mCarrierRoamingNtnSignalStrength[i]);
// We need to obfuscate package names, and primitive arrays' native toString is ugly
Pair<List<String>, int[]> carrierPrivilegeState = mCarrierPrivilegeStates.get(i);
diff --git a/services/core/java/com/android/server/adaptiveauth/OWNERS b/services/core/java/com/android/server/adaptiveauth/OWNERS
deleted file mode 100644
index b18810564d88..000000000000
--- a/services/core/java/com/android/server/adaptiveauth/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-hainingc@google.com \ No newline at end of file
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 18e8abb6e884..0826c5333e2f 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -19307,18 +19307,31 @@ public class ActivityManagerService extends IActivityManager.Stub
public void addCreatorToken(@Nullable Intent intent, String creatorPackage) {
if (!preventIntentRedirect()) return;
- if (intent == null) return;
- intent.forEachNestedCreatorToken(extraIntent -> {
- IntentCreatorToken creatorToken = createIntentCreatorToken(extraIntent, creatorPackage);
- if (creatorToken != null) {
- extraIntent.setCreatorToken(creatorToken);
- // TODO remove Slog.wtf once proven FrameworkStatsLog works. b/375396329
- Slog.wtf(TAG, "A creator token is added to an intent. creatorPackage: "
- + creatorPackage + "; intent: " + intent);
- FrameworkStatsLog.write(INTENT_CREATOR_TOKEN_ADDED,
- creatorToken.getCreatorUid());
+ if (intent == null || intent.getExtraIntentKeys() == null) return;
+ for (String key : intent.getExtraIntentKeys()) {
+ try {
+ Intent extraIntent = intent.getParcelableExtra(key, Intent.class);
+ if (extraIntent == null) {
+ Slog.w(TAG, "The key {" + key
+ + "} does not correspond to an intent in the extra bundle.");
+ continue;
+ }
+ IntentCreatorToken creatorToken = createIntentCreatorToken(extraIntent,
+ creatorPackage);
+ if (creatorToken != null) {
+ extraIntent.setCreatorToken(creatorToken);
+ Slog.wtf(TAG, "A creator token is added to an intent. creatorPackage: "
+ + creatorPackage + "; intent: " + intent);
+ FrameworkStatsLog.write(INTENT_CREATOR_TOKEN_ADDED,
+ creatorToken.getCreatorUid());
+ }
+ } catch (Exception e) {
+ Slog.wtf(TAG,
+ "Something went wrong when trying to add creator token for embedded "
+ + "intents of intent: ."
+ + intent, e);
}
- });
+ }
}
private IntentCreatorToken createIntentCreatorToken(Intent intent, String creatorPackage) {
diff --git a/services/core/java/com/android/server/am/BroadcastController.java b/services/core/java/com/android/server/am/BroadcastController.java
index b0f880710eb6..8a128582c507 100644
--- a/services/core/java/com/android/server/am/BroadcastController.java
+++ b/services/core/java/com/android/server/am/BroadcastController.java
@@ -593,7 +593,7 @@ class BroadcastController {
originalStickyCallingUid, BackgroundStartPrivileges.NONE,
false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */,
null /* filterExtrasForReceiver */,
- broadcast.originalCallingAppProcessState);
+ broadcast.originalCallingAppProcessState, mService.mPlatformCompat);
queue.enqueueBroadcastLocked(r);
}
}
@@ -1631,7 +1631,7 @@ class BroadcastController {
receivers, resultToApp, resultTo, resultCode, resultData, resultExtras,
ordered, sticky, false, userId,
backgroundStartPrivileges, timeoutExempt, filterExtrasForReceiver,
- callerAppProcessState);
+ callerAppProcessState, mService.mPlatformCompat);
broadcastSentEventRecord.setBroadcastRecord(r);
if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
diff --git a/services/core/java/com/android/server/am/BroadcastRecord.java b/services/core/java/com/android/server/am/BroadcastRecord.java
index f908c67d7ec9..116aeeaa35c1 100644
--- a/services/core/java/com/android/server/am/BroadcastRecord.java
+++ b/services/core/java/com/android/server/am/BroadcastRecord.java
@@ -42,6 +42,9 @@ import android.app.AppOpsManager;
import android.app.BackgroundStartPrivileges;
import android.app.BroadcastOptions;
import android.app.BroadcastOptions.DeliveryGroupPolicy;
+import android.compat.annotation.ChangeId;
+import android.compat.annotation.EnabledSince;
+import android.compat.annotation.Overridable;
import android.content.ComponentName;
import android.content.IIntentReceiver;
import android.content.Intent;
@@ -55,10 +58,12 @@ import android.os.UserHandle;
import android.util.ArrayMap;
import android.util.IntArray;
import android.util.PrintWriterPrinter;
+import android.util.SparseBooleanArray;
import android.util.TimeUtils;
import android.util.proto.ProtoOutputStream;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.compat.PlatformCompat;
import dalvik.annotation.optimization.NeverCompile;
@@ -77,6 +82,16 @@ import java.util.function.BiFunction;
* An active intent broadcast.
*/
final class BroadcastRecord extends Binder {
+ /**
+ * Limit the scope of the priority values to the process level. This means that priority values
+ * will only influence the order of broadcast delivery within the same process.
+ */
+ @ChangeId
+ @EnabledSince(targetSdkVersion = android.os.Build.VERSION_CODES.BASE)
+ @Overridable
+ @VisibleForTesting
+ static final long CHANGE_LIMIT_PRIORITY_SCOPE = 371307720L;
+
final @NonNull Intent intent; // the original intent that generated us
final @Nullable ComponentName targetComp; // original component name set on the intent
final @Nullable ProcessRecord callerApp; // process that sent this
@@ -417,13 +432,13 @@ final class BroadcastRecord extends Binder {
@NonNull BackgroundStartPrivileges backgroundStartPrivileges,
boolean timeoutExempt,
@Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver,
- int callerAppProcessState) {
+ int callerAppProcessState, PlatformCompat platformCompat) {
this(queue, intent, callerApp, callerPackage, callerFeatureId, callingPid,
callingUid, callerInstantApp, resolvedType, requiredPermissions,
excludedPermissions, excludedPackages, appOp, options, receivers, resultToApp,
resultTo, resultCode, resultData, resultExtras, serialized, sticky,
initialSticky, userId, -1, backgroundStartPrivileges, timeoutExempt,
- filterExtrasForReceiver, callerAppProcessState);
+ filterExtrasForReceiver, callerAppProcessState, platformCompat);
}
BroadcastRecord(BroadcastQueue _queue,
@@ -439,7 +454,7 @@ final class BroadcastRecord extends Binder {
@NonNull BackgroundStartPrivileges backgroundStartPrivileges,
boolean timeoutExempt,
@Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver,
- int callerAppProcessState) {
+ int callerAppProcessState, PlatformCompat platformCompat) {
if (_intent == null) {
throw new NullPointerException("Can't construct with a null intent");
}
@@ -466,7 +481,8 @@ final class BroadcastRecord extends Binder {
urgent = calculateUrgent(_intent, _options);
deferUntilActive = calculateDeferUntilActive(_callingUid,
_options, _resultTo, _serialized, urgent);
- blockedUntilBeyondCount = calculateBlockedUntilBeyondCount(receivers, _serialized);
+ blockedUntilBeyondCount = calculateBlockedUntilBeyondCount(
+ receivers, _serialized, platformCompat);
scheduledTime = new long[delivery.length];
terminalTime = new long[delivery.length];
resultToApp = _resultToApp;
@@ -730,7 +746,8 @@ final class BroadcastRecord extends Binder {
}
/**
- * Determine if the result of {@link #calculateBlockedUntilBeyondCount(List, boolean)}
+ * Determine if the result of
+ * {@link #calculateBlockedUntilBeyondCount(List, boolean, PlatformCompat)}
* has prioritized tranches of receivers.
*/
@VisibleForTesting
@@ -754,37 +771,121 @@ final class BroadcastRecord extends Binder {
*/
@VisibleForTesting
static @NonNull int[] calculateBlockedUntilBeyondCount(
- @NonNull List<Object> receivers, boolean ordered) {
+ @NonNull List<Object> receivers, boolean ordered, PlatformCompat platformCompat) {
final int N = receivers.size();
final int[] blockedUntilBeyondCount = new int[N];
- int lastPriority = 0;
- int lastPriorityIndex = 0;
- for (int i = 0; i < N; i++) {
- if (ordered) {
- // When sending an ordered broadcast, we need to block this
- // receiver until all previous receivers have terminated
+ if (ordered) {
+ // When sending an ordered broadcast, we need to block this
+ // receiver until all previous receivers have terminated
+ for (int i = 0; i < N; i++) {
blockedUntilBeyondCount[i] = i;
+ }
+ } else {
+ if (Flags.limitPriorityScope()) {
+ final boolean[] changeEnabled = calculateChangeStateForReceivers(
+ receivers, CHANGE_LIMIT_PRIORITY_SCOPE, platformCompat);
+
+ // Priority of the previous tranche
+ int lastTranchePriority = 0;
+ // Priority of the current tranche
+ int currentTranchePriority = 0;
+ // Index of the last receiver in the previous tranche
+ int lastTranchePriorityIndex = -1;
+ // Index of the last receiver with change disabled in the previous tranche
+ int lastTrancheChangeDisabledIndex = -1;
+ // Index of the last receiver with change disabled in the current tranche
+ int currentTrancheChangeDisabledIndex = -1;
+
+ for (int i = 0; i < N; i++) {
+ final int thisPriority = getReceiverPriority(receivers.get(i));
+ if (i == 0) {
+ currentTranchePriority = thisPriority;
+ if (!changeEnabled[i]) {
+ currentTrancheChangeDisabledIndex = i;
+ }
+ continue;
+ }
+
+ // Check if a new priority tranche has started
+ if (thisPriority != currentTranchePriority) {
+ // Update tranche boundaries and reset the disabled index.
+ if (currentTrancheChangeDisabledIndex != -1) {
+ lastTrancheChangeDisabledIndex = currentTrancheChangeDisabledIndex;
+ }
+ lastTranchePriority = currentTranchePriority;
+ lastTranchePriorityIndex = i - 1;
+ currentTranchePriority = thisPriority;
+ currentTrancheChangeDisabledIndex = -1;
+ }
+ if (!changeEnabled[i]) {
+ currentTrancheChangeDisabledIndex = i;
+
+ // Since the change is disabled, block the current receiver until the
+ // last receiver in the previous tranche.
+ blockedUntilBeyondCount[i] = lastTranchePriorityIndex + 1;
+ } else if (thisPriority != lastTranchePriority) {
+ // If the changeId was disabled for an earlier receiver and the current
+ // receiver has a different priority, block the current receiver
+ // until that earlier receiver.
+ if (lastTrancheChangeDisabledIndex != -1) {
+ blockedUntilBeyondCount[i] = lastTrancheChangeDisabledIndex + 1;
+ }
+ }
+ }
+ // If the entire list is in the same priority tranche or no receivers had
+ // changeId disabled, mark as -1 to indicate that none of them need to wait
+ if (N > 0 && (lastTranchePriorityIndex == -1
+ || (lastTrancheChangeDisabledIndex == -1
+ && currentTrancheChangeDisabledIndex == -1))) {
+ Arrays.fill(blockedUntilBeyondCount, -1);
+ }
} else {
// When sending a prioritized broadcast, we only need to wait
// for the previous tranche of receivers to be terminated
- final int thisPriority = getReceiverPriority(receivers.get(i));
- if ((i == 0) || (thisPriority != lastPriority)) {
- lastPriority = thisPriority;
- lastPriorityIndex = i;
- blockedUntilBeyondCount[i] = i;
- } else {
- blockedUntilBeyondCount[i] = lastPriorityIndex;
+ int lastPriority = 0;
+ int lastPriorityIndex = 0;
+ for (int i = 0; i < N; i++) {
+ final int thisPriority = getReceiverPriority(receivers.get(i));
+ if ((i == 0) || (thisPriority != lastPriority)) {
+ lastPriority = thisPriority;
+ lastPriorityIndex = i;
+ blockedUntilBeyondCount[i] = i;
+ } else {
+ blockedUntilBeyondCount[i] = lastPriorityIndex;
+ }
+ }
+ // If the entire list is in the same priority tranche, mark as -1 to
+ // indicate that none of them need to wait
+ if (N > 0 && blockedUntilBeyondCount[N - 1] == 0) {
+ Arrays.fill(blockedUntilBeyondCount, -1);
}
}
}
- // If the entire list is in the same priority tranche, mark as -1 to
- // indicate that none of them need to wait
- if (N > 0 && blockedUntilBeyondCount[N - 1] == 0) {
- Arrays.fill(blockedUntilBeyondCount, -1);
- }
return blockedUntilBeyondCount;
}
+ @VisibleForTesting
+ static @NonNull boolean[] calculateChangeStateForReceivers(@NonNull List<Object> receivers,
+ long changeId, PlatformCompat platformCompat) {
+ final SparseBooleanArray changeStateForUids = new SparseBooleanArray();
+ final int count = receivers.size();
+ final boolean[] changeStateForReceivers = new boolean[count];
+ for (int i = 0; i < count; ++i) {
+ final int receiverUid = getReceiverUid(receivers.get(i));
+ final boolean isChangeEnabled;
+ final int idx = changeStateForUids.indexOfKey(receiverUid);
+ if (idx >= 0) {
+ isChangeEnabled = changeStateForUids.valueAt(idx);
+ } else {
+ isChangeEnabled = platformCompat.isChangeEnabledByUidInternalNoLogging(
+ changeId, receiverUid);
+ changeStateForUids.put(receiverUid, isChangeEnabled);
+ }
+ changeStateForReceivers[i] = isChangeEnabled;
+ }
+ return changeStateForReceivers;
+ }
+
static int getReceiverUid(@NonNull Object receiver) {
if (receiver instanceof BroadcastFilter) {
return ((BroadcastFilter) receiver).owningUid;
diff --git a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
index 8dc7c7345f79..3dd5ec9a3834 100644
--- a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
+++ b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
@@ -42,6 +42,7 @@ import android.aconfigd.Aconfigd.StorageReturnMessages;
import static com.android.aconfig_new_storage.Flags.enableAconfigStorageDaemon;
import static com.android.aconfig_new_storage.Flags.supportImmediateLocalOverrides;
import static com.android.aconfig_new_storage.Flags.supportClearLocalOverridesImmediately;
+import static com.android.aconfig.flags.Flags.enableSystemAconfigdRust;
import java.io.DataInputStream;
import java.io.DataOutputStream;
@@ -144,7 +145,6 @@ public class SettingsToPropertiesMapper {
"android_core_networking",
"android_health_services",
"android_sdk",
- "android_stylus",
"aoc",
"app_widgets",
"arc_next",
@@ -209,6 +209,7 @@ public class SettingsToPropertiesMapper {
"pixel_continuity",
"pixel_perf",
"pixel_sensors",
+ "pixel_state_server",
"pixel_system_sw_video",
"pixel_video_sw",
"pixel_watch",
@@ -456,9 +457,11 @@ public class SettingsToPropertiesMapper {
static ProtoInputStream sendAconfigdRequests(ProtoOutputStream requests) {
// connect to aconfigd socket
LocalSocket client = new LocalSocket();
+ String socketName = enableSystemAconfigdRust()
+ ? "aconfigd_system" : "aconfigd";
try{
client.connect(new LocalSocketAddress(
- "aconfigd", LocalSocketAddress.Namespace.RESERVED));
+ socketName, LocalSocketAddress.Namespace.RESERVED));
Slog.d(TAG, "connected to aconfigd socket");
} catch (IOException ioe) {
logErr("failed to connect to aconfigd socket", ioe);
diff --git a/services/core/java/com/android/server/am/broadcasts_flags.aconfig b/services/core/java/com/android/server/am/broadcasts_flags.aconfig
index b1185d552941..7f169db7dcec 100644
--- a/services/core/java/com/android/server/am/broadcasts_flags.aconfig
+++ b/services/core/java/com/android/server/am/broadcasts_flags.aconfig
@@ -7,4 +7,12 @@ flag {
description: "Restrict priority values defined by non-system apps"
is_fixed_read_only: true
bug: "369487976"
+}
+
+flag {
+ name: "limit_priority_scope"
+ namespace: "backstage_power"
+ description: "Limit the scope of receiver priorities to within a process"
+ is_fixed_read_only: true
+ bug: "369487976"
} \ No newline at end of file
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index 0cf55bb2bf17..6ba356990cac 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -9193,16 +9193,6 @@ public class AudioService extends IAudioService.Stub
mIndexMin = MIN_STREAM_VOLUME[streamType] * 10;
mIndexMax = MAX_STREAM_VOLUME[streamType] * 10;
- final int status = AudioSystem.initStreamVolume(
- streamType, MIN_STREAM_VOLUME[streamType], MAX_STREAM_VOLUME[streamType]);
- if (status != AudioSystem.AUDIO_STATUS_OK) {
- sLifecycleLogger.enqueue(new EventLogger.StringEvent(
- "VSS() stream:" + streamType + " initStreamVolume=" + status)
- .printLog(ALOGE, TAG));
- sendMsg(mAudioHandler, MSG_REINIT_VOLUMES, SENDMSG_NOOP, 0, 0,
- "VSS()" /*obj*/, 2 * INDICATE_SYSTEM_READY_RETRY_DELAY_MS);
- }
-
updateIndexFactors();
mIndexMinNoPerm = mIndexMin; // may be overwritten later in updateNoPermMinIndex()
@@ -9267,6 +9257,19 @@ public class AudioService extends IAudioService.Stub
mIndexMinNoPerm = mIndexMin;
}
}
+
+ final int status = AudioSystem.initStreamVolume(
+ mStreamType, mIndexMin / 10, mIndexMax / 10);
+ sVolumeLogger.enqueue(new EventLogger.StringEvent(
+ "updateIndexFactors() stream:" + mStreamType + " index min/max:"
+ + mIndexMin / 10 + "/" + mIndexMax / 10 + " indexStepFactor:"
+ + mIndexStepFactor).printSlog(ALOGI, TAG));
+ if (status != AudioSystem.AUDIO_STATUS_OK) {
+ sVolumeLogger.enqueue(new EventLogger.StringEvent(
+ "Failed initStreamVolume with status=" + status).printSlog(ALOGE, TAG));
+ sendMsg(mAudioHandler, MSG_REINIT_VOLUMES, SENDMSG_NOOP, 0, 0,
+ "updateIndexFactors()" /*obj*/, 2 * INDICATE_SYSTEM_READY_RETRY_DELAY_MS);
+ }
}
/**
diff --git a/services/core/java/com/android/server/biometrics/BiometricService.java b/services/core/java/com/android/server/biometrics/BiometricService.java
index 00280c8f9c04..65780238ede4 100644
--- a/services/core/java/com/android/server/biometrics/BiometricService.java
+++ b/services/core/java/com/android/server/biometrics/BiometricService.java
@@ -288,11 +288,13 @@ public class BiometricService extends SystemService {
* @param handler The handler to run {@link #onChange} on, or null if none.
*/
public SettingObserver(Context context, Handler handler,
- List<BiometricService.EnabledOnKeyguardCallback> callbacks) {
+ List<BiometricService.EnabledOnKeyguardCallback> callbacks,
+ UserManager userManager, FingerprintManager fingerprintManager,
+ FaceManager faceManager) {
super(handler);
mContentResolver = context.getContentResolver();
mCallbacks = callbacks;
- mUserManager = context.getSystemService(UserManager.class);
+ mUserManager = userManager;
final boolean hasFingerprint = context.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
@@ -304,7 +306,7 @@ public class BiometricService extends SystemService {
Build.VERSION.DEVICE_INITIAL_SDK_INT <= Build.VERSION_CODES.Q
&& hasFace && !hasFingerprint;
- addBiometricListenersForMandatoryBiometrics(context);
+ addBiometricListenersForMandatoryBiometrics(context, fingerprintManager, faceManager);
updateContentObserver();
}
@@ -431,11 +433,21 @@ public class BiometricService extends SystemService {
public boolean getMandatoryBiometricsEnabledAndRequirementsSatisfiedForUser(int userId) {
if (!mMandatoryBiometricsEnabled.containsKey(userId)) {
+ Slog.d(TAG, "update mb toggle for user " + userId);
updateMandatoryBiometricsForAllProfiles(userId);
}
if (!mMandatoryBiometricsRequirementsSatisfied.containsKey(userId)) {
+ Slog.d(TAG, "update mb reqs for user " + userId);
updateMandatoryBiometricsRequirementsForAllProfiles(userId);
}
+
+ Slog.d(TAG, mMandatoryBiometricsEnabled.getOrDefault(userId,
+ DEFAULT_MANDATORY_BIOMETRICS_STATUS)
+ + " " + mMandatoryBiometricsRequirementsSatisfied.getOrDefault(userId,
+ DEFAULT_MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED_STATUS)
+ + " " + getEnabledForApps(userId)
+ + " " + (mFingerprintEnrolledForUser.getOrDefault(userId, false /* default */)
+ || mFaceEnrolledForUser.getOrDefault(userId, false /* default */)));
return mMandatoryBiometricsEnabled.getOrDefault(userId,
DEFAULT_MANDATORY_BIOMETRICS_STATUS)
&& mMandatoryBiometricsRequirementsSatisfied.getOrDefault(userId,
@@ -456,11 +468,23 @@ public class BiometricService extends SystemService {
private void updateMandatoryBiometricsForAllProfiles(int userId) {
int effectiveUserId = userId;
- if (mUserManager.getMainUser() != null) {
- effectiveUserId = mUserManager.getMainUser().getIdentifier();
+ final UserInfo parentProfile = mUserManager.getProfileParent(userId);
+
+ if (parentProfile != null) {
+ effectiveUserId = parentProfile.id;
}
- for (int profileUserId: mUserManager.getEnabledProfileIds(effectiveUserId)) {
- mMandatoryBiometricsEnabled.put(profileUserId,
+
+ final int[] enabledProfileIds = mUserManager.getEnabledProfileIds(effectiveUserId);
+ if (enabledProfileIds != null) {
+ for (int profileUserId : enabledProfileIds) {
+ mMandatoryBiometricsEnabled.put(profileUserId,
+ Settings.Secure.getIntForUser(
+ mContentResolver, Settings.Secure.MANDATORY_BIOMETRICS,
+ DEFAULT_MANDATORY_BIOMETRICS_STATUS ? 1 : 0,
+ effectiveUserId) != 0);
+ }
+ } else {
+ mMandatoryBiometricsEnabled.put(userId,
Settings.Secure.getIntForUser(
mContentResolver, Settings.Secure.MANDATORY_BIOMETRICS,
DEFAULT_MANDATORY_BIOMETRICS_STATUS ? 1 : 0,
@@ -470,11 +494,24 @@ public class BiometricService extends SystemService {
private void updateMandatoryBiometricsRequirementsForAllProfiles(int userId) {
int effectiveUserId = userId;
- if (mUserManager.getMainUser() != null) {
- effectiveUserId = mUserManager.getMainUser().getIdentifier();
+ final UserInfo parentProfile = mUserManager.getProfileParent(userId);
+
+ if (parentProfile != null) {
+ effectiveUserId = parentProfile.id;
}
- for (int profileUserId: mUserManager.getEnabledProfileIds(effectiveUserId)) {
- mMandatoryBiometricsRequirementsSatisfied.put(profileUserId,
+
+ final int[] enabledProfileIds = mUserManager.getEnabledProfileIds(effectiveUserId);
+ if (enabledProfileIds != null) {
+ for (int profileUserId : enabledProfileIds) {
+ mMandatoryBiometricsRequirementsSatisfied.put(profileUserId,
+ Settings.Secure.getIntForUser(mContentResolver,
+ Settings.Secure.MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED,
+ DEFAULT_MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED_STATUS
+ ? 1 : 0,
+ effectiveUserId) != 0);
+ }
+ } else {
+ mMandatoryBiometricsRequirementsSatisfied.put(userId,
Settings.Secure.getIntForUser(mContentResolver,
Settings.Secure.MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED,
DEFAULT_MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED_STATUS ? 1 : 0,
@@ -482,10 +519,8 @@ public class BiometricService extends SystemService {
}
}
- private void addBiometricListenersForMandatoryBiometrics(Context context) {
- final FingerprintManager fingerprintManager = context.getSystemService(
- FingerprintManager.class);
- final FaceManager faceManager = context.getSystemService(FaceManager.class);
+ private void addBiometricListenersForMandatoryBiometrics(Context context,
+ FingerprintManager fingerprintManager, FaceManager faceManager) {
if (fingerprintManager != null) {
fingerprintManager.addAuthenticatorsRegisteredCallback(
new IFingerprintAuthenticatorsRegisteredCallback.Stub() {
@@ -1169,7 +1204,9 @@ public class BiometricService extends SystemService {
*/
public SettingObserver getSettingObserver(Context context, Handler handler,
List<EnabledOnKeyguardCallback> callbacks) {
- return new SettingObserver(context, handler, callbacks);
+ return new SettingObserver(context, handler, callbacks, context.getSystemService(
+ UserManager.class), context.getSystemService(FingerprintManager.class),
+ context.getSystemService(FaceManager.class));
}
/**
diff --git a/services/core/java/com/android/server/input/InputGestureManager.java b/services/core/java/com/android/server/input/InputGestureManager.java
index e545dd507f28..2e7f5c083ac3 100644
--- a/services/core/java/com/android/server/input/InputGestureManager.java
+++ b/services/core/java/com/android/server/input/InputGestureManager.java
@@ -215,6 +215,12 @@ final class InputGestureManager {
systemShortcuts.add(createKeyGesture(KeyEvent.KEYCODE_T,
KeyEvent.META_META_ON | KeyEvent.META_ALT_ON,
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_TALKBACK));
+ systemShortcuts.add(createKeyGesture(KeyEvent.KEYCODE_MINUS,
+ KeyEvent.META_META_ON | KeyEvent.META_ALT_ON,
+ KeyGestureEvent.KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_OUT));
+ systemShortcuts.add(createKeyGesture(KeyEvent.KEYCODE_EQUALS,
+ KeyEvent.META_META_ON | KeyEvent.META_ALT_ON,
+ KeyGestureEvent.KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_IN));
}
if (keyboardA11yShortcutControl()) {
if (InputSettings.isAccessibilityBounceKeysFeatureEnabled()) {
diff --git a/services/core/java/com/android/server/input/KeyGestureController.java b/services/core/java/com/android/server/input/KeyGestureController.java
index 155ffe805519..0124e25f0655 100644
--- a/services/core/java/com/android/server/input/KeyGestureController.java
+++ b/services/core/java/com/android/server/input/KeyGestureController.java
@@ -20,6 +20,7 @@ import static android.content.pm.PackageManager.FEATURE_LEANBACK;
import static android.content.pm.PackageManager.FEATURE_WATCH;
import static android.view.WindowManagerPolicyConstants.FLAG_INTERACTIVE;
+import static com.android.hardware.input.Flags.enableNew25q2Keycodes;
import static com.android.hardware.input.Flags.useKeyGestureEventHandler;
import static com.android.hardware.input.Flags.useKeyGestureEventHandlerMultiPressGestures;
@@ -750,6 +751,28 @@ final class KeyGestureController {
}
}
break;
+ case KeyEvent.KEYCODE_LOCK:
+ if (enableNew25q2Keycodes()) {
+ if (firstDown) {
+ handleKeyGesture(deviceId, new int[]{KeyEvent.KEYCODE_LOCK},
+ /* modifierState = */0,
+ KeyGestureEvent.KEY_GESTURE_TYPE_LOCK_SCREEN,
+ KeyGestureEvent.ACTION_GESTURE_COMPLETE, displayId, focusedToken,
+ /* flags = */0, /* appLaunchData = */null);
+ }
+ }
+ return true;
+ case KeyEvent.KEYCODE_FULLSCREEN:
+ if (enableNew25q2Keycodes()) {
+ if (firstDown) {
+ handleKeyGesture(deviceId, new int[]{KeyEvent.KEYCODE_FULLSCREEN},
+ /* modifierState = */0,
+ KeyGestureEvent.KEY_GESTURE_TYPE_MAXIMIZE_FREEFORM_WINDOW,
+ KeyGestureEvent.ACTION_GESTURE_COMPLETE, displayId, focusedToken,
+ /* flags = */0, /* appLaunchData = */null);
+ }
+ }
+ return true;
case KeyEvent.KEYCODE_ASSIST:
Slog.wtf(TAG, "KEYCODE_ASSIST should be handled in interceptKeyBeforeQueueing");
return true;
@@ -764,6 +787,9 @@ final class KeyGestureController {
Slog.wtf(TAG, "KEYCODE_STYLUS_BUTTON_* should be handled in"
+ " interceptKeyBeforeQueueing");
return true;
+ case KeyEvent.KEYCODE_DO_NOT_DISTURB:
+ // TODO(b/365920375): Implement 25Q2 keycode implementation in system
+ return true;
}
// Handle custom shortcuts
diff --git a/services/core/java/com/android/server/media/quality/MediaQualityService.java b/services/core/java/com/android/server/media/quality/MediaQualityService.java
index a45ea1d8369d..21ae1820f6f7 100644
--- a/services/core/java/com/android/server/media/quality/MediaQualityService.java
+++ b/services/core/java/com/android/server/media/quality/MediaQualityService.java
@@ -59,15 +59,15 @@ public class MediaQualityService extends SystemService {
return pp;
}
@Override
- public void updatePictureProfile(long id, PictureProfile pp) {
+ public void updatePictureProfile(String id, PictureProfile pp) {
// TODO: implement
}
@Override
- public void removePictureProfile(long id) {
+ public void removePictureProfile(String id) {
// TODO: implement
}
@Override
- public PictureProfile getPictureProfileById(long id) {
+ public PictureProfile getPictureProfile(int type, String name) {
return null;
}
@Override
@@ -79,7 +79,7 @@ public class MediaQualityService extends SystemService {
return new ArrayList<>();
}
@Override
- public List<PictureProfile> getAllPictureProfiles() {
+ public List<String> getPictureProfilePackageNames() {
return new ArrayList<>();
}
@@ -89,15 +89,15 @@ public class MediaQualityService extends SystemService {
return pp;
}
@Override
- public void updateSoundProfile(long id, SoundProfile pp) {
+ public void updateSoundProfile(String id, SoundProfile pp) {
// TODO: implement
}
@Override
- public void removeSoundProfile(long id) {
+ public void removeSoundProfile(String id) {
// TODO: implement
}
@Override
- public SoundProfile getSoundProfileById(long id) {
+ public SoundProfile getSoundProfileById(String id) {
return null;
}
@Override
@@ -109,7 +109,7 @@ public class MediaQualityService extends SystemService {
return new ArrayList<>();
}
@Override
- public List<SoundProfile> getAllSoundProfiles() {
+ public List<String> getSoundProfilePackageNames() {
return new ArrayList<>();
}
@@ -138,6 +138,14 @@ public class MediaQualityService extends SystemService {
return new ArrayList<>();
}
+ @Override
+ public List<String> getPictureProfileAllowList() {
+ return new ArrayList<>();
+ }
+
+ @Override
+ public void setPictureProfileAllowList(List<String> packages) {
+ }
@Override
public boolean isSupported() {
diff --git a/services/core/java/com/android/server/notification/GroupHelper.java b/services/core/java/com/android/server/notification/GroupHelper.java
index 5febd5c07e3a..5914dbe44b0b 100644
--- a/services/core/java/com/android/server/notification/GroupHelper.java
+++ b/services/core/java/com/android/server/notification/GroupHelper.java
@@ -788,6 +788,20 @@ public class GroupHelper {
return;
}
+ // Check if summary & child notifications are not part of the same section/bundle
+ // Needs a check here if notification was bundled while enqueued
+ if (notificationRegroupOnClassification()
+ && android.service.notification.Flags.notificationClassification()) {
+ if (isGroupChildBundled(record, summaryByGroupKey)) {
+ if (DEBUG) {
+ Slog.v(TAG, "isGroupChildInDifferentBundleThanSummary: " + record);
+ }
+ moveNotificationsToNewSection(record.getUserId(), pkgName,
+ List.of(new NotificationMoveOp(record, null, fullAggregateGroupKey)));
+ return;
+ }
+ }
+
// scenario 3: sparse/singleton groups
if (Flags.notificationForceGroupSingletons()) {
try {
@@ -800,6 +814,27 @@ public class GroupHelper {
}
}
+ private static boolean isGroupChildBundled(final NotificationRecord record,
+ final Map<String, NotificationRecord> summaryByGroupKey) {
+ final StatusBarNotification sbn = record.getSbn();
+ final String groupKey = record.getSbn().getGroupKey();
+
+ if (!sbn.isAppGroup()) {
+ return false;
+ }
+
+ if (record.getNotification().isGroupSummary()) {
+ return false;
+ }
+
+ final NotificationRecord summary = summaryByGroupKey.get(groupKey);
+ if (summary == null) {
+ return false;
+ }
+
+ return NotificationChannel.SYSTEM_RESERVED_IDS.contains(record.getChannel().getId());
+ }
+
/**
* Called when a notification is removed, so that this helper can adjust the aggregate groups:
* - Removes the autogroup summary of the notification's section
@@ -1598,7 +1633,7 @@ public class GroupHelper {
final int mSummaryId;
private final Predicate<NotificationRecord> mSectionChecker;
- public NotificationSectioner(String name, int summaryId,
+ private NotificationSectioner(String name, int summaryId,
Predicate<NotificationRecord> sectionChecker) {
mName = name;
mSummaryId = summaryId;
diff --git a/services/core/java/com/android/server/notification/ManagedServices.java b/services/core/java/com/android/server/notification/ManagedServices.java
index 93482e769a2b..b0ef80793cd7 100644
--- a/services/core/java/com/android/server/notification/ManagedServices.java
+++ b/services/core/java/com/android/server/notification/ManagedServices.java
@@ -75,9 +75,7 @@ import com.android.internal.util.XmlUtils;
import com.android.internal.util.function.TriPredicate;
import com.android.modules.utils.TypedXmlPullParser;
import com.android.modules.utils.TypedXmlSerializer;
-import com.android.server.LocalServices;
import com.android.server.notification.NotificationManagerService.DumpFilter;
-import com.android.server.pm.UserManagerInternal;
import com.android.server.utils.TimingsTraceAndSlog;
import org.xmlpull.v1.XmlPullParser;
@@ -136,7 +134,6 @@ abstract public class ManagedServices {
private final UserProfiles mUserProfiles;
protected final IPackageManager mPm;
protected final UserManager mUm;
- private final UserManagerInternal mUserManagerInternal;
private final Config mConfig;
private final Handler mHandler = new Handler(Looper.getMainLooper());
@@ -198,7 +195,6 @@ abstract public class ManagedServices {
mConfig = getConfig();
mApprovalLevel = APPROVAL_BY_COMPONENT;
mUm = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
- mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
}
abstract protected Config getConfig();
@@ -1389,14 +1385,9 @@ abstract public class ManagedServices {
@GuardedBy("mMutex")
protected void populateComponentsToBind(SparseArray<Set<ComponentName>> componentsToBind,
final IntArray activeUsers,
- SparseArray<ArraySet<ComponentName>> approvedComponentsByUser,
- boolean isVisibleBackgroundUser) {
- // When it is a visible background user in Automotive MUMD environment,
- // don't clear mEnabledServicesForCurrentProfile and mEnabledServicesPackageNames.
- if (!isVisibleBackgroundUser) {
- mEnabledServicesForCurrentProfiles.clear();
- mEnabledServicesPackageNames.clear();
- }
+ SparseArray<ArraySet<ComponentName>> approvedComponentsByUser) {
+ mEnabledServicesForCurrentProfiles.clear();
+ mEnabledServicesPackageNames.clear();
final int nUserIds = activeUsers.size();
for (int i = 0; i < nUserIds; ++i) {
@@ -1417,12 +1408,7 @@ abstract public class ManagedServices {
}
componentsToBind.put(userId, add);
- // When it is a visible background user in Automotive MUMD environment,
- // skip adding items to mEnabledServicesForCurrentProfile
- // and mEnabledServicesPackageNames.
- if (isVisibleBackgroundUser) {
- continue;
- }
+
mEnabledServicesForCurrentProfiles.addAll(userComponents);
for (int j = 0; j < userComponents.size(); j++) {
@@ -1470,10 +1456,7 @@ abstract public class ManagedServices {
IntArray userIds = mUserProfiles.getCurrentProfileIds();
boolean rebindAllCurrentUsers = mUserProfiles.isProfileUser(userToRebind, mContext)
&& allowRebindForParentUser();
- boolean isVisibleBackgroundUser = false;
if (userToRebind != USER_ALL && !rebindAllCurrentUsers) {
- isVisibleBackgroundUser =
- mUserManagerInternal.isVisibleBackgroundFullUser(userToRebind);
userIds = new IntArray(1);
userIds.add(userToRebind);
}
@@ -1488,8 +1471,7 @@ abstract public class ManagedServices {
// Filter approvedComponentsByUser to collect all of the components that are allowed
// for the currently active user(s).
- populateComponentsToBind(componentsToBind, userIds, approvedComponentsByUser,
- isVisibleBackgroundUser);
+ populateComponentsToBind(componentsToBind, userIds, approvedComponentsByUser);
// For every current non-system connection, disconnect services that are no longer
// approved, or ALL services if we are force rebinding
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 19406b46f5c0..8d039f19db8c 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -83,7 +83,7 @@ import static android.view.WindowManagerGlobal.ADD_OKAY;
import static android.view.WindowManagerGlobal.ADD_PERMISSION_DENIED;
import static android.view.contentprotection.flags.Flags.createAccessibilityOverlayAppOpEnabled;
-import static com.android.hardware.input.Flags.emojiAndScreenshotKeycodesAvailable;
+import static com.android.hardware.input.Flags.enableNew25q2Keycodes;
import static com.android.hardware.input.Flags.enableTalkbackAndMagnifierKeyGestures;
import static com.android.hardware.input.Flags.keyboardA11yShortcutControl;
import static com.android.hardware.input.Flags.modifierShortcutDump;
@@ -3993,10 +3993,14 @@ public class PhoneWindowManager implements WindowManagerPolicy {
return true;
}
case KeyEvent.KEYCODE_SCREENSHOT:
- if (emojiAndScreenshotKeycodesAvailable() && down && repeatCount == 0) {
+ if (firstDown) {
interceptScreenshotChord(SCREENSHOT_KEY_OTHER, 0 /*pressDelay*/);
}
return true;
+ case KeyEvent.KEYCODE_DO_NOT_DISTURB:
+ case KeyEvent.KEYCODE_LOCK:
+ case KeyEvent.KEYCODE_FULLSCREEN:
+ return true;
}
if (isValidGlobalKey(keyCode)
&& mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
@@ -5666,9 +5670,23 @@ public class PhoneWindowManager implements WindowManagerPolicy {
case KeyEvent.KEYCODE_MACRO_4:
result &= ~ACTION_PASS_TO_USER;
break;
- case KeyEvent.KEYCODE_EMOJI_PICKER:
- if (!emojiAndScreenshotKeycodesAvailable()) {
- // Don't allow EMOJI_PICKER key to be dispatched until flag is released.
+ case KeyEvent.KEYCODE_DICTATE:
+ case KeyEvent.KEYCODE_NEW:
+ case KeyEvent.KEYCODE_CLOSE:
+ case KeyEvent.KEYCODE_PRINT:
+ case KeyEvent.KEYCODE_F13:
+ case KeyEvent.KEYCODE_F14:
+ case KeyEvent.KEYCODE_F15:
+ case KeyEvent.KEYCODE_F16:
+ case KeyEvent.KEYCODE_F17:
+ case KeyEvent.KEYCODE_F18:
+ case KeyEvent.KEYCODE_F19:
+ case KeyEvent.KEYCODE_F20:
+ case KeyEvent.KEYCODE_F21:
+ case KeyEvent.KEYCODE_F22:
+ case KeyEvent.KEYCODE_F23:
+ case KeyEvent.KEYCODE_F24:
+ if (!enableNew25q2Keycodes()) {
result &= ~ACTION_PASS_TO_USER;
}
break;
@@ -5841,8 +5859,8 @@ public class PhoneWindowManager implements WindowManagerPolicy {
public int interceptMotionBeforeQueueingNonInteractive(int displayId, int source, int action,
long whenNanos, int policyFlags) {
if ((policyFlags & FLAG_WAKE) != 0) {
- if (mWindowWakeUpPolicy.wakeUpFromMotion(
- whenNanos / 1000000, source, action == MotionEvent.ACTION_DOWN)) {
+ if (mWindowWakeUpPolicy.wakeUpFromMotion(displayId, whenNanos / 1000000, source,
+ action == MotionEvent.ACTION_DOWN)) {
// Woke up. Pass motion events to user.
return ACTION_PASS_TO_USER;
}
@@ -5856,8 +5874,8 @@ public class PhoneWindowManager implements WindowManagerPolicy {
// there will be no dream to intercept the touch and wake into ambient. The device should
// wake up in this case.
if (isTheaterModeEnabled() && (policyFlags & FLAG_WAKE) != 0) {
- if (mWindowWakeUpPolicy.wakeUpFromMotion(
- whenNanos / 1000000, source, action == MotionEvent.ACTION_DOWN)) {
+ if (mWindowWakeUpPolicy.wakeUpFromMotion(displayId, whenNanos / 1000000, source,
+ action == MotionEvent.ACTION_DOWN)) {
// Woke up. Pass motion events to user.
return ACTION_PASS_TO_USER;
}
@@ -6205,7 +6223,7 @@ public class PhoneWindowManager implements WindowManagerPolicy {
}
private void wakeUpFromWakeKey(long eventTime, int keyCode, boolean isDown) {
- if (mWindowWakeUpPolicy.wakeUpFromKey(eventTime, keyCode, isDown)) {
+ if (mWindowWakeUpPolicy.wakeUpFromKey(DEFAULT_DISPLAY, eventTime, keyCode, isDown)) {
final boolean keyCanLaunchHome = keyCode == KEYCODE_HOME || keyCode == KEYCODE_POWER;
// Start HOME with "reason" extra if sleeping for more than mWakeUpToLastStateTimeout
if (shouldWakeUpWithHomeIntent() && keyCanLaunchHome) {
diff --git a/services/core/java/com/android/server/policy/WindowWakeUpPolicy.java b/services/core/java/com/android/server/policy/WindowWakeUpPolicy.java
index af1ad13f1d15..04dbd1fea5d6 100644
--- a/services/core/java/com/android/server/policy/WindowWakeUpPolicy.java
+++ b/services/core/java/com/android/server/policy/WindowWakeUpPolicy.java
@@ -25,6 +25,7 @@ import static android.os.PowerManager.WAKE_REASON_WAKE_MOTION;
import static android.view.KeyEvent.KEYCODE_POWER;
import static com.android.server.policy.Flags.supportInputWakeupDelegate;
+import static com.android.server.power.feature.flags.Flags.perDisplayWakeByTouch;
import android.annotation.Nullable;
import android.content.Context;
@@ -107,13 +108,14 @@ class WindowWakeUpPolicy {
/**
* Wakes up from a key event.
*
+ * @param displayId the id of the display to wake.
* @param eventTime the timestamp of the event in {@link SystemClock#uptimeMillis()}.
* @param keyCode the {@link android.view.KeyEvent} key code of the key event.
* @param isDown {@code true} if the event's action is {@link KeyEvent#ACTION_DOWN}.
* @return {@code true} if the policy allows the requested wake up and the request has been
* executed; {@code false} otherwise.
*/
- boolean wakeUpFromKey(long eventTime, int keyCode, boolean isDown) {
+ boolean wakeUpFromKey(int displayId, long eventTime, int keyCode, boolean isDown) {
final boolean wakeAllowedDuringTheaterMode =
keyCode == KEYCODE_POWER
? mAllowTheaterModeWakeFromPowerKey
@@ -126,22 +128,31 @@ class WindowWakeUpPolicy {
&& mInputWakeUpDelegate.wakeUpFromKey(eventTime, keyCode, isDown)) {
return true;
}
- wakeUp(
- eventTime,
- keyCode == KEYCODE_POWER ? WAKE_REASON_POWER_BUTTON : WAKE_REASON_WAKE_KEY,
- keyCode == KEYCODE_POWER ? "POWER" : "KEY");
+ if (perDisplayWakeByTouch()) {
+ wakeUp(
+ displayId,
+ eventTime,
+ keyCode == KEYCODE_POWER ? WAKE_REASON_POWER_BUTTON : WAKE_REASON_WAKE_KEY,
+ keyCode == KEYCODE_POWER ? "POWER" : "KEY");
+ } else {
+ wakeUp(
+ eventTime,
+ keyCode == KEYCODE_POWER ? WAKE_REASON_POWER_BUTTON : WAKE_REASON_WAKE_KEY,
+ keyCode == KEYCODE_POWER ? "POWER" : "KEY");
+ }
return true;
}
/**
* Wakes up from a motion event.
*
+ * @param displayId the id of the display to wake.
* @param eventTime the timestamp of the event in {@link SystemClock#uptimeMillis()}.
* @param isDown {@code true} if the event's action is {@link MotionEvent#ACTION_DOWN}.
* @return {@code true} if the policy allows the requested wake up and the request has been
* executed; {@code false} otherwise.
*/
- boolean wakeUpFromMotion(long eventTime, int source, boolean isDown) {
+ boolean wakeUpFromMotion(int displayId, long eventTime, int source, boolean isDown) {
if (!canWakeUp(mAllowTheaterModeWakeFromMotion)) {
if (DEBUG) Slog.d(TAG, "Unable to wake up from motion.");
return false;
@@ -150,7 +161,11 @@ class WindowWakeUpPolicy {
&& mInputWakeUpDelegate.wakeUpFromMotion(eventTime, source, isDown)) {
return true;
}
- wakeUp(eventTime, WAKE_REASON_WAKE_MOTION, "MOTION");
+ if (perDisplayWakeByTouch()) {
+ wakeUp(displayId, eventTime, WAKE_REASON_WAKE_MOTION, "MOTION");
+ } else {
+ wakeUp(eventTime, WAKE_REASON_WAKE_MOTION, "MOTION");
+ }
return true;
}
@@ -237,4 +252,12 @@ class WindowWakeUpPolicy {
private void wakeUp(long wakeTime, @WakeReason int reason, String details) {
mPowerManager.wakeUp(wakeTime, reason, "android.policy:" + details);
}
+
+ /** Wakes up given display. */
+ private void wakeUp(int displayId, long wakeTime, @WakeReason int reason, String details) {
+ // If we're given an invalid display id to wake, fall back to waking default display
+ final int displayIdToWake =
+ displayId == Display.INVALID_DISPLAY ? Display.DEFAULT_DISPLAY : displayId;
+ mPowerManager.wakeUp(wakeTime, reason, "android.policy:" + details, displayIdToWake);
+ }
}
diff --git a/services/core/java/com/android/server/adaptiveauth/AdaptiveAuthService.java b/services/core/java/com/android/server/security/adaptiveauthentication/AdaptiveAuthenticationService.java
index 9398c7a854d4..b129fdc1b6e3 100644
--- a/services/core/java/com/android/server/adaptiveauth/AdaptiveAuthService.java
+++ b/services/core/java/com/android/server/security/adaptiveauthentication/AdaptiveAuthenticationService.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.adaptiveauth;
+package com.android.server.security.adaptiveauthentication;
import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_ADAPTIVE_AUTH_REQUEST;
@@ -55,8 +55,8 @@ import java.util.Objects;
/**
* @hide
*/
-public class AdaptiveAuthService extends SystemService {
- private static final String TAG = "AdaptiveAuthService";
+public class AdaptiveAuthenticationService extends SystemService {
+ private static final String TAG = "AdaptiveAuthenticationService";
private static final boolean DEBUG = Build.IS_DEBUGGABLE && Log.isLoggable(TAG, Log.DEBUG);
@VisibleForTesting
@@ -78,12 +78,12 @@ public class AdaptiveAuthService extends SystemService {
final SparseIntArray mFailedAttemptsForUser = new SparseIntArray();
private final SparseLongArray mLastLockedTimestamp = new SparseLongArray();
- public AdaptiveAuthService(Context context) {
+ public AdaptiveAuthenticationService(Context context) {
this(context, new LockPatternUtils(context));
}
@VisibleForTesting
- public AdaptiveAuthService(Context context, LockPatternUtils lockPatternUtils) {
+ public AdaptiveAuthenticationService(Context context, LockPatternUtils lockPatternUtils) {
super(context);
mLockPatternUtils = lockPatternUtils;
mLockSettings = Objects.requireNonNull(
diff --git a/services/core/java/com/android/server/security/adaptiveauthentication/OWNERS b/services/core/java/com/android/server/security/adaptiveauthentication/OWNERS
new file mode 100644
index 000000000000..29affcdb81aa
--- /dev/null
+++ b/services/core/java/com/android/server/security/adaptiveauthentication/OWNERS
@@ -0,0 +1,3 @@
+hainingc@google.com
+jbolinger@google.com
+graciecheng@google.com
diff --git a/services/core/java/com/android/server/wm/BackgroundActivityStartController.java b/services/core/java/com/android/server/wm/BackgroundActivityStartController.java
index ec171c5e5766..a71620d66f80 100644
--- a/services/core/java/com/android/server/wm/BackgroundActivityStartController.java
+++ b/services/core/java/com/android/server/wm/BackgroundActivityStartController.java
@@ -46,10 +46,8 @@ import static com.android.server.wm.ActivityTaskSupervisor.getApplicationLabel;
import static com.android.server.wm.PendingRemoteAnimationRegistry.TIMEOUT_MS;
import static com.android.window.flags.Flags.balAdditionalStartModes;
import static com.android.window.flags.Flags.balDontBringExistingBackgroundTaskStackToFg;
-import static com.android.window.flags.Flags.balImproveRealCallerVisibilityCheck;
import static com.android.window.flags.Flags.balImprovedMetrics;
import static com.android.window.flags.Flags.balRequireOptInByPendingIntentCreator;
-import static com.android.window.flags.Flags.balRespectAppSwitchStateWhenCheckBoundByForegroundUid;
import static com.android.window.flags.Flags.balShowToastsBlocked;
import static com.android.window.flags.Flags.balStrictModeRo;
@@ -348,11 +346,7 @@ public class BackgroundActivityStartController {
@BackgroundActivityStartMode int realCallerBackgroundActivityStartMode =
checkedOptions.getPendingIntentBackgroundActivityStartMode();
- if (!balImproveRealCallerVisibilityCheck()) {
- // without this fix the auto-opt ins below would violate CTS tests
- mAutoOptInReason = null;
- mAutoOptInCaller = false;
- } else if (originatingPendingIntent == null) {
+ if (originatingPendingIntent == null) {
mAutoOptInReason = AUTO_OPT_IN_NOT_PENDING_INTENT;
mAutoOptInCaller = true;
} else if (mIsCallForResult) {
@@ -599,12 +593,8 @@ public class BackgroundActivityStartController {
mCheckedOptions.getPendingIntentBackgroundActivityStartMode()));
}
// features
- sb.append("; balImproveRealCallerVisibilityCheck: ")
- .append(balImproveRealCallerVisibilityCheck());
sb.append("; balRequireOptInByPendingIntentCreator: ")
.append(balRequireOptInByPendingIntentCreator());
- sb.append("; balRespectAppSwitchStateWhenCheckBoundByForegroundUid: ")
- .append(balRespectAppSwitchStateWhenCheckBoundByForegroundUid());
sb.append("; balDontBringExistingBackgroundTaskStackToFg: ")
.append(balDontBringExistingBackgroundTaskStackToFg());
sb.append("]");
@@ -1133,23 +1123,13 @@ public class BackgroundActivityStartController {
final boolean appSwitchAllowedOrFg = state.mAppSwitchState == APP_SWITCH_ALLOW
|| state.mAppSwitchState == APP_SWITCH_FG_ONLY
|| isHomeApp(state.mRealCallingUid, state.mRealCallingPackage);
- if (balImproveRealCallerVisibilityCheck()) {
- if (appSwitchAllowedOrFg && state.mRealCallingUidHasAnyVisibleWindow) {
- return new BalVerdict(BAL_ALLOW_VISIBLE_WINDOW,
- /*background*/ false, "realCallingUid has visible window");
- }
- if (mService.mActiveUids.hasNonAppVisibleWindow(state.mRealCallingUid)) {
- return new BalVerdict(BAL_ALLOW_NON_APP_VISIBLE_WINDOW,
- /*background*/ false, "realCallingUid has non-app visible window");
- }
- } else {
- // don't abort if the realCallingUid has a visible window
- // TODO(b/171459802): We should check appSwitchAllowed also
- if (state.mRealCallingUidHasAnyVisibleWindow) {
- return new BalVerdict(BAL_ALLOW_VISIBLE_WINDOW,
- /*background*/ false,
- "realCallingUid has visible (non-toast) window.");
- }
+ if (appSwitchAllowedOrFg && state.mRealCallingUidHasAnyVisibleWindow) {
+ return new BalVerdict(BAL_ALLOW_VISIBLE_WINDOW,
+ /*background*/ false, "realCallingUid has visible window");
+ }
+ if (mService.mActiveUids.hasNonAppVisibleWindow(state.mRealCallingUid)) {
+ return new BalVerdict(BAL_ALLOW_NON_APP_VISIBLE_WINDOW,
+ /*background*/ false, "realCallingUid has non-app visible window");
}
// Don't abort if the realCallerApp or other processes of that uid are considered to be in
diff --git a/services/core/java/com/android/server/wm/BackgroundLaunchProcessController.java b/services/core/java/com/android/server/wm/BackgroundLaunchProcessController.java
index 264c8beb44bf..ccf1aedb3177 100644
--- a/services/core/java/com/android/server/wm/BackgroundLaunchProcessController.java
+++ b/services/core/java/com/android/server/wm/BackgroundLaunchProcessController.java
@@ -50,7 +50,6 @@ import android.util.IntArray;
import com.android.internal.annotations.GuardedBy;
import com.android.server.wm.BackgroundActivityStartController.BalVerdict;
-import com.android.window.flags.Flags;
import java.io.PrintWriter;
import java.util.ArrayList;
@@ -137,10 +136,8 @@ class BackgroundLaunchProcessController {
}
// Allow if the caller is bound by a UID that's currently foreground.
// But still respect the appSwitchState.
- if (checkConfiguration.checkVisibility && (
- Flags.balRespectAppSwitchStateWhenCheckBoundByForegroundUid()
- ? appSwitchState != APP_SWITCH_DISALLOW && isBoundByForegroundUid()
- : isBoundByForegroundUid())) {
+ if (checkConfiguration.checkVisibility && appSwitchState != APP_SWITCH_DISALLOW
+ && isBoundByForegroundUid()) {
return new BalVerdict(balImprovedMetrics() ? BAL_ALLOW_BOUND_BY_FOREGROUND
: BAL_ALLOW_VISIBLE_WINDOW, /*background*/ false,
"process bound by foreground uid");
diff --git a/services/core/java/com/android/server/wm/Transition.java b/services/core/java/com/android/server/wm/Transition.java
index a6034664af5a..20481f25fa5c 100644
--- a/services/core/java/com/android/server/wm/Transition.java
+++ b/services/core/java/com/android/server/wm/Transition.java
@@ -465,6 +465,31 @@ class Transition implements BLASTSyncEngine.TransactionReadyListener {
return false;
}
+ /**
+ * This ensures that all changes for previously transient-hide containers are flagged such that
+ * they will report changes and be included in this transition.
+ */
+ void updateChangesForRestoreTransientHideTasks(Transition transientLaunchTransition) {
+ if (transientLaunchTransition.mTransientHideTasks == null) {
+ // Skip if the transient-launch transition has no transient-hide tasks
+ ProtoLog.v(WmProtoLogGroups.WM_DEBUG_WINDOW_TRANSITIONS,
+ "Skipping update changes for restore transient hide tasks");
+ return;
+ }
+
+ // For each change, if it was previously transient-hidden, then we should force a flag to
+ // ensure that it is included in the next transition
+ for (int i = 0; i < mChanges.size(); i++) {
+ final WindowContainer container = mChanges.keyAt(i);
+ if (transientLaunchTransition.isInTransientHide(container)) {
+ ProtoLog.v(WmProtoLogGroups.WM_DEBUG_WINDOW_TRANSITIONS,
+ "Force update transient hide task for restore %d: %s", mSyncId, container);
+ final ChangeInfo info = mChanges.valueAt(i);
+ info.mRestoringTransientHide = true;
+ }
+ }
+ }
+
/** Returns {@code true} if the task should keep visible if this is a transient transition. */
boolean isTransientVisible(@NonNull Task task) {
if (mTransientLaunches == null) return false;
@@ -3478,6 +3503,10 @@ class Transition implements BLASTSyncEngine.TransactionReadyListener {
// State tracking
boolean mExistenceChanged = false;
+ // This state indicates that we are restoring transient order as a part of an
+ // end-transition. Because the visibility for transient hide containers has not actually
+ // changed, we need to ensure that hasChanged() still reports the relevant changes
+ boolean mRestoringTransientHide = false;
// before change state
boolean mVisible;
int mWindowingMode;
@@ -3552,7 +3581,11 @@ class Transition implements BLASTSyncEngine.TransactionReadyListener {
|| !mContainer.getBounds().equals(mAbsoluteBounds)
|| mRotation != mContainer.getWindowConfiguration().getRotation()
|| mDisplayId != getDisplayId(mContainer)
- || (mFlags & ChangeInfo.FLAG_CHANGE_MOVED_TO_TOP) != 0;
+ || (mFlags & ChangeInfo.FLAG_CHANGE_MOVED_TO_TOP) != 0
+ // If we are restoring transient-hide containers, then we should consider them
+ // important for the transition as well (their requested visibilities would not
+ // have changed for the checks below to consider it).
+ || mRestoringTransientHide;
}
@TransitionInfo.TransitionMode
@@ -3565,6 +3598,11 @@ class Transition implements BLASTSyncEngine.TransactionReadyListener {
}
final boolean nowVisible = wc.isVisibleRequested();
if (nowVisible == mVisible) {
+ if (mRestoringTransientHide) {
+ // The requested visibility has not changed for transient-hide containers, but
+ // we are restoring them so we should considering them moving to front again
+ return TRANSIT_TO_FRONT;
+ }
return TRANSIT_CHANGE;
}
if (mExistenceChanged) {
diff --git a/services/core/java/com/android/server/wm/TransitionController.java b/services/core/java/com/android/server/wm/TransitionController.java
index 87bdfa4f5d75..143d1b72fff9 100644
--- a/services/core/java/com/android/server/wm/TransitionController.java
+++ b/services/core/java/com/android/server/wm/TransitionController.java
@@ -37,6 +37,7 @@ import android.os.RemoteException;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.util.ArrayMap;
+import android.util.Pair;
import android.util.Slog;
import android.util.SparseArray;
import android.util.TimeUtils;
@@ -524,6 +525,23 @@ class TransitionController {
return false;
}
+ /**
+ * @return A pair of the transition and restore-behind target for the given {@param container}.
+ * @param container An ancestor of a transient-launch activity
+ */
+ @Nullable
+ Pair<Transition, Task> getTransientLaunchTransitionAndTarget(
+ @NonNull WindowContainer container) {
+ for (int i = mPlayingTransitions.size() - 1; i >= 0; --i) {
+ final Transition transition = mPlayingTransitions.get(i);
+ final Task restoreBehindTask = transition.getTransientLaunchRestoreTarget(container);
+ if (restoreBehindTask != null) {
+ return new Pair<>(transition, restoreBehindTask);
+ }
+ }
+ return null;
+ }
+
/** Returns {@code true} if the display contains a transient-launch transition. */
boolean hasTransientLaunch(@NonNull DisplayContent dc) {
if (mCollectingTransition != null && mCollectingTransition.hasTransientLaunch()
diff --git a/services/core/java/com/android/server/wm/WindowOrganizerController.java b/services/core/java/com/android/server/wm/WindowOrganizerController.java
index dac8f69a4cae..ead12826c263 100644
--- a/services/core/java/com/android/server/wm/WindowOrganizerController.java
+++ b/services/core/java/com/android/server/wm/WindowOrganizerController.java
@@ -111,6 +111,7 @@ import android.os.RemoteException;
import android.util.AndroidRuntimeException;
import android.util.ArrayMap;
import android.util.ArraySet;
+import android.util.Pair;
import android.util.Slog;
import android.view.RemoteAnimationAdapter;
import android.view.SurfaceControl;
@@ -1375,16 +1376,56 @@ class WindowOrganizerController extends IWindowOrganizerController.Stub
break;
}
case HIERARCHY_OP_TYPE_RESTORE_TRANSIENT_ORDER: {
- if (!chain.isFinishing()) break;
+ if (!com.android.wm.shell.Flags.enableShellTopTaskTracking()) {
+ // Only allow restoring transient order when finishing a transition
+ if (!chain.isFinishing()) break;
+ }
+ // Validate the container
final WindowContainer container = WindowContainer.fromBinder(hop.getContainer());
- if (container == null) break;
+ if (container == null) {
+ ProtoLog.v(WmProtoLogGroups.WM_DEBUG_WINDOW_TRANSITIONS,
+ "Restoring transient order: invalid container");
+ break;
+ }
final Task thisTask = container.asActivityRecord() != null
? container.asActivityRecord().getTask() : container.asTask();
- if (thisTask == null) break;
- final Task restoreAt = chain.mTransition.getTransientLaunchRestoreTarget(container);
- if (restoreAt == null) break;
+ if (thisTask == null) {
+ ProtoLog.v(WmProtoLogGroups.WM_DEBUG_WINDOW_TRANSITIONS,
+ "Restoring transient order: invalid task");
+ break;
+ }
+
+ // Find the task to restore behind
+ final Pair<Transition, Task> transientRestore =
+ mTransitionController.getTransientLaunchTransitionAndTarget(container);
+ if (transientRestore == null) {
+ ProtoLog.v(WmProtoLogGroups.WM_DEBUG_WINDOW_TRANSITIONS,
+ "Restoring transient order: no restore task");
+ break;
+ }
+ final Transition transientLaunchTransition = transientRestore.first;
+ final Task restoreAt = transientRestore.second;
+ ProtoLog.v(WmProtoLogGroups.WM_DEBUG_WINDOW_TRANSITIONS,
+ "Restoring transient order: restoring behind task=%d", restoreAt.mTaskId);
+
+ // Restore the position of the given container behind the target task
final TaskDisplayArea taskDisplayArea = thisTask.getTaskDisplayArea();
taskDisplayArea.moveRootTaskBehindRootTask(thisTask.getRootTask(), restoreAt);
+
+ if (com.android.wm.shell.Flags.enableShellTopTaskTracking()) {
+ // Because we are in a transient launch transition, the requested visibility of
+ // tasks does not actually change for the transient-hide tasks, but we do want
+ // the restoration of these transient-hide tasks to top to be a part of this
+ // finish transition
+ final Transition collectingTransition =
+ mTransitionController.getCollectingTransition();
+ if (collectingTransition != null) {
+ collectingTransition.updateChangesForRestoreTransientHideTasks(
+ transientLaunchTransition);
+ }
+ }
+
+ effects |= TRANSACT_EFFECTS_LIFECYCLE;
break;
}
case HIERARCHY_OP_TYPE_ADD_INSETS_FRAME_PROVIDER: {
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 221b8481a30c..9759772ae8bd 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -119,7 +119,6 @@ import com.android.internal.widget.ILockSettings;
import com.android.internal.widget.LockSettingsInternal;
import com.android.server.accessibility.AccessibilityManagerService;
import com.android.server.accounts.AccountManagerService;
-import com.android.server.adaptiveauth.AdaptiveAuthService;
import com.android.server.adb.AdbService;
import com.android.server.alarm.AlarmManagerService;
import com.android.server.am.ActivityManagerService;
@@ -250,6 +249,7 @@ import com.android.server.security.AttestationVerificationManagerService;
import com.android.server.security.FileIntegrityService;
import com.android.server.security.KeyAttestationApplicationIdProviderService;
import com.android.server.security.KeyChainSystemService;
+import com.android.server.security.adaptiveauthentication.AdaptiveAuthenticationService;
import com.android.server.security.advancedprotection.AdvancedProtectionService;
import com.android.server.security.rkp.RemoteProvisioningService;
import com.android.server.selinux.SelinuxAuditLogsService;
@@ -2651,8 +2651,8 @@ public final class SystemServer implements Dumpable {
t.traceEnd();
if (android.adaptiveauth.Flags.enableAdaptiveAuth()) {
- t.traceBegin("StartAdaptiveAuthService");
- mSystemServiceManager.startService(AdaptiveAuthService.class);
+ t.traceBegin("StartAdaptiveAuthenticationService");
+ mSystemServiceManager.startService(AdaptiveAuthenticationService.class);
t.traceEnd();
}
diff --git a/services/tests/mockingservicestests/Android.bp b/services/tests/mockingservicestests/Android.bp
index be698b2673ad..979384c6b2db 100644
--- a/services/tests/mockingservicestests/Android.bp
+++ b/services/tests/mockingservicestests/Android.bp
@@ -134,6 +134,7 @@ android_ravenwood_test {
"androidx.annotation_annotation",
"androidx.test.rules",
"services.core",
+ "servicestests-utils-mockito-extended",
],
srcs: [
"src/com/android/server/am/BroadcastRecordTest.java",
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/ActivityManagerServiceTest.java b/services/tests/mockingservicestests/src/com/android/server/am/ActivityManagerServiceTest.java
index dcbc23410fdb..2a825f35bf62 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/ActivityManagerServiceTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/ActivityManagerServiceTest.java
@@ -1308,8 +1308,6 @@ public class ActivityManagerServiceTest {
Intent intent = new Intent();
Intent extraIntent = new Intent("EXTRA_INTENT_ACTION");
intent.putExtra("EXTRA_INTENT0", extraIntent);
- Intent nestedIntent = new Intent("NESTED_INTENT_ACTION");
- extraIntent.putExtra("NESTED_INTENT", nestedIntent);
intent.collectExtraIntentKeys();
mAms.addCreatorToken(intent, TEST_PACKAGE);
@@ -1319,11 +1317,6 @@ public class ActivityManagerServiceTest {
assertThat(token).isNotNull();
assertThat(token.getCreatorUid()).isEqualTo(mInjector.getCallingUid());
assertThat(token.getCreatorPackage()).isEqualTo(TEST_PACKAGE);
-
- token = (ActivityManagerService.IntentCreatorToken) nestedIntent.getCreatorToken();
- assertThat(token).isNotNull();
- assertThat(token.getCreatorUid()).isEqualTo(mInjector.getCallingUid());
- assertThat(token.getCreatorPackage()).isEqualTo(TEST_PACKAGE);
}
@Test
@@ -1356,8 +1349,6 @@ public class ActivityManagerServiceTest {
Intent intent = new Intent();
Intent extraIntent = new Intent("EXTRA_INTENT_ACTION");
intent.putExtra("EXTRA_INTENT", extraIntent);
- Intent nestedIntent = new Intent("NESTED_INTENT_ACTION");
- extraIntent.putExtra("NESTED_INTENT", nestedIntent);
intent.collectExtraIntentKeys();
@@ -1383,12 +1374,9 @@ public class ActivityManagerServiceTest {
extraIntent = intent.getParcelableExtra("EXTRA_INTENT", Intent.class);
extraIntent2 = intent.getParcelableExtra("EXTRA_INTENT2", Intent.class);
extraIntent3 = intent.getParcelableExtra("EXTRA_INTENT3", Intent.class);
- nestedIntent = extraIntent.getParcelableExtra("NESTED_INTENT", Intent.class);
assertThat(extraIntent.getExtendedFlags()
& Intent.EXTENDED_FLAG_MISSING_CREATOR_OR_INVALID_TOKEN).isEqualTo(0);
- assertThat(nestedIntent.getExtendedFlags()
- & Intent.EXTENDED_FLAG_MISSING_CREATOR_OR_INVALID_TOKEN).isEqualTo(0);
// sneaked in intent should have EXTENDED_FLAG_MISSING_CREATOR_OR_INVALID_TOKEN set.
assertThat(extraIntent2.getExtendedFlags()
& Intent.EXTENDED_FLAG_MISSING_CREATOR_OR_INVALID_TOKEN).isNotEqualTo(0);
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/BaseBroadcastQueueTest.java b/services/tests/mockingservicestests/src/com/android/server/am/BaseBroadcastQueueTest.java
index d602660597ff..a1a8b0ec7d2f 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/BaseBroadcastQueueTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/BaseBroadcastQueueTest.java
@@ -41,6 +41,7 @@ import android.os.TestLooperManager;
import android.os.UserHandle;
import android.platform.test.flag.junit.CheckFlagsRule;
import android.platform.test.flag.junit.DeviceFlagsValueProvider;
+import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.Settings;
import android.util.SparseArray;
@@ -97,6 +98,9 @@ public abstract class BaseBroadcastQueueTest {
.spyStatic(ProcessList.class)
.build();
+
+ @Rule
+ public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Rule
public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
@@ -112,6 +116,8 @@ public abstract class BaseBroadcastQueueTest {
AlarmManagerInternal mAlarmManagerInt;
@Mock
ProcessList mProcessList;
+ @Mock
+ PlatformCompat mPlatformCompat;
@Mock
AppStartInfoTracker mAppStartInfoTracker;
@@ -178,6 +184,11 @@ public abstract class BaseBroadcastQueueTest {
doReturn(false).when(mSkipPolicy).disallowBackgroundStart(any());
doReturn(mAppStartInfoTracker).when(mProcessList).getAppStartInfoTracker();
+
+ doReturn(true).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastFilter.CHANGE_RESTRICT_PRIORITY_VALUES), anyInt());
+ doReturn(true).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), anyInt());
}
public void tearDown() throws Exception {
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueModernImplTest.java b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueModernImplTest.java
index 100b54897573..1481085c5f71 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueModernImplTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueModernImplTest.java
@@ -18,6 +18,7 @@ package com.android.server.am;
import static android.app.ActivityManager.PROCESS_STATE_UNKNOWN;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED;
import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD;
@@ -49,7 +50,6 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
@@ -65,7 +65,6 @@ import android.content.IIntentReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
-import android.content.pm.ResolveInfo;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.BundleMerger;
@@ -73,6 +72,8 @@ import android.os.DropBoxManager;
import android.os.Process;
import android.os.SystemClock;
import android.os.UserHandle;
+import android.platform.test.annotations.DisableFlags;
+import android.platform.test.annotations.EnableFlags;
import android.util.IndentingPrintWriter;
import android.util.Pair;
@@ -182,10 +183,6 @@ public final class BroadcastQueueModernImplTest extends BaseBroadcastQueueTest {
return mock(Intent.class);
}
- private static ResolveInfo makeMockManifestReceiver() {
- return mock(ResolveInfo.class);
- }
-
private static BroadcastFilter makeMockRegisteredReceiver() {
return mock(BroadcastFilter.class);
}
@@ -214,7 +211,8 @@ public final class BroadcastQueueModernImplTest extends BaseBroadcastQueueTest {
return new BroadcastRecord(mImpl, intent, mProcess, PACKAGE_RED, null, 21, TEST_UID, false,
null, null, null, null, AppOpsManager.OP_NONE, options, receivers, null, resultTo,
Activity.RESULT_OK, null, null, ordered, false, false, UserHandle.USER_SYSTEM,
- BackgroundStartPrivileges.NONE, false, null, PROCESS_STATE_UNKNOWN);
+ BackgroundStartPrivileges.NONE, false, null, PROCESS_STATE_UNKNOWN,
+ mPlatformCompat);
}
private void enqueueOrReplaceBroadcast(BroadcastProcessQueue queue,
@@ -646,7 +644,8 @@ public final class BroadcastQueueModernImplTest extends BaseBroadcastQueueTest {
@Test
public void testRunnableAt_Cached_Manifest() {
doRunnableAt_Cached(makeBroadcastRecord(makeMockIntent(), null,
- List.of(makeMockManifestReceiver()), null, false), REASON_CONTAINS_MANIFEST);
+ List.of(makeManifestReceiver(PACKAGE_RED, CLASS_RED)), null, false),
+ REASON_CONTAINS_MANIFEST);
}
@Test
@@ -679,6 +678,19 @@ public final class BroadcastQueueModernImplTest extends BaseBroadcastQueueTest {
List.of(makeMockRegisteredReceiver()), null, false), REASON_CONTAINS_ALARM);
}
+ @DisableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testRunnableAt_Cached_Prioritized_NonDeferrable_flagDisabled() {
+ final List receivers = List.of(
+ withPriority(makeManifestReceiver(PACKAGE_RED, PACKAGE_RED), 10),
+ withPriority(makeManifestReceiver(PACKAGE_GREEN, PACKAGE_GREEN), -10));
+ final BroadcastOptions options = BroadcastOptions.makeBasic()
+ .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_NONE);
+ doRunnableAt_Cached(makeBroadcastRecord(makeMockIntent(), options,
+ receivers, null, false), REASON_CONTAINS_PRIORITIZED);
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
public void testRunnableAt_Cached_Prioritized_NonDeferrable() {
final List receivers = List.of(
@@ -687,6 +699,32 @@ public final class BroadcastQueueModernImplTest extends BaseBroadcastQueueTest {
final BroadcastOptions options = BroadcastOptions.makeBasic()
.setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_NONE);
doRunnableAt_Cached(makeBroadcastRecord(makeMockIntent(), options,
+ receivers, null, false), REASON_CONTAINS_MANIFEST);
+ }
+
+ @Test
+ public void testRunnableAt_Cached_Ordered_NonDeferrable() {
+ final List receivers = List.of(
+ withPriority(makeManifestReceiver(PACKAGE_RED, PACKAGE_RED), 10),
+ withPriority(makeManifestReceiver(PACKAGE_GREEN, PACKAGE_GREEN), -10));
+ final BroadcastOptions options = BroadcastOptions.makeBasic()
+ .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_NONE);
+ doRunnableAt_Cached(makeBroadcastRecord(makeMockIntent(), options,
+ receivers, mock(IIntentReceiver.class), true), REASON_CONTAINS_ORDERED);
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testRunnableAt_Cached_Prioritized_NonDeferrable_changeIdDisabled() {
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE),
+ eq(getUidForPackage(PACKAGE_GREEN)));
+ final List receivers = List.of(
+ withPriority(makeManifestReceiver(PACKAGE_RED, PACKAGE_RED), 10),
+ withPriority(makeManifestReceiver(PACKAGE_GREEN, PACKAGE_GREEN), -10));
+ final BroadcastOptions options = BroadcastOptions.makeBasic()
+ .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_NONE);
+ doRunnableAt_Cached(makeBroadcastRecord(makeMockIntent(), options,
receivers, null, false), REASON_CONTAINS_PRIORITIZED);
}
@@ -1136,6 +1174,63 @@ public final class BroadcastQueueModernImplTest extends BaseBroadcastQueueTest {
verifyPendingRecords(blueQueue, List.of(screenOn));
}
+ @DisableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @SuppressWarnings("GuardedBy")
+ @Test
+ public void testDeliveryGroupPolicy_prioritized_diffReceivers_flagDisabled() {
+ final Intent screenOn = new Intent(Intent.ACTION_SCREEN_ON);
+ final Intent screenOff = new Intent(Intent.ACTION_SCREEN_OFF);
+ final BroadcastOptions screenOnOffOptions = BroadcastOptions.makeBasic()
+ .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
+ .setDeliveryGroupMatchingKey("screenOnOff", Intent.ACTION_SCREEN_ON);
+
+ final Object greenReceiver = withPriority(
+ makeManifestReceiver(PACKAGE_GREEN, CLASS_GREEN), 10);
+ final Object redReceiver = withPriority(
+ makeManifestReceiver(PACKAGE_RED, CLASS_RED), 5);
+ final Object blueReceiver = withPriority(
+ makeManifestReceiver(PACKAGE_BLUE, CLASS_BLUE), 0);
+
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOn, screenOnOffOptions,
+ List.of(greenReceiver, blueReceiver), false));
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOff, screenOnOffOptions,
+ List.of(greenReceiver, redReceiver, blueReceiver), false));
+ final BroadcastProcessQueue greenQueue = mImpl.getProcessQueue(PACKAGE_GREEN,
+ getUidForPackage(PACKAGE_GREEN));
+ final BroadcastProcessQueue redQueue = mImpl.getProcessQueue(PACKAGE_RED,
+ getUidForPackage(PACKAGE_RED));
+ final BroadcastProcessQueue blueQueue = mImpl.getProcessQueue(PACKAGE_BLUE,
+ getUidForPackage(PACKAGE_BLUE));
+ verifyPendingRecords(greenQueue, List.of(screenOff));
+ verifyPendingRecords(redQueue, List.of(screenOff));
+ verifyPendingRecords(blueQueue, List.of(screenOff));
+
+ assertTrue(greenQueue.isEmpty());
+ assertTrue(redQueue.isEmpty());
+ assertTrue(blueQueue.isEmpty());
+
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOff, screenOnOffOptions,
+ List.of(greenReceiver, redReceiver, blueReceiver), false));
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOn, screenOnOffOptions,
+ List.of(greenReceiver, blueReceiver), false));
+ verifyPendingRecords(greenQueue, List.of(screenOff, screenOn));
+ verifyPendingRecords(redQueue, List.of(screenOff));
+ verifyPendingRecords(blueQueue, List.of(screenOff, screenOn));
+
+ final BroadcastRecord screenOffRecord = makeBroadcastRecord(screenOff, screenOnOffOptions,
+ List.of(greenReceiver, redReceiver, blueReceiver), false);
+ screenOffRecord.setDeliveryState(2, BroadcastRecord.DELIVERY_DEFERRED,
+ "testDeliveryGroupPolicy_prioritized_diffReceivers_flagDisabled");
+ mImpl.enqueueBroadcastLocked(screenOffRecord);
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOn, screenOnOffOptions,
+ List.of(greenReceiver, blueReceiver), false));
+ verifyPendingRecords(greenQueue, List.of(screenOff, screenOn));
+ verifyPendingRecords(redQueue, List.of(screenOff));
+ verifyPendingRecords(blueQueue, List.of(screenOn));
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @SuppressWarnings("GuardedBy")
@Test
public void testDeliveryGroupPolicy_prioritized_diffReceivers() {
final Intent screenOn = new Intent(Intent.ACTION_SCREEN_ON);
@@ -1173,6 +1268,65 @@ public final class BroadcastQueueModernImplTest extends BaseBroadcastQueueTest {
List.of(greenReceiver, redReceiver, blueReceiver), false));
mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOn, screenOnOffOptions,
List.of(greenReceiver, blueReceiver), false));
+ verifyPendingRecords(greenQueue, List.of(screenOn));
+ verifyPendingRecords(redQueue, List.of(screenOff));
+ verifyPendingRecords(blueQueue, List.of(screenOn));
+
+ final BroadcastRecord screenOffRecord = makeBroadcastRecord(screenOff, screenOnOffOptions,
+ List.of(greenReceiver, redReceiver, blueReceiver), false);
+ screenOffRecord.setDeliveryState(2, BroadcastRecord.DELIVERY_DEFERRED,
+ "testDeliveryGroupPolicy_prioritized_diffReceivers");
+ mImpl.enqueueBroadcastLocked(screenOffRecord);
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOn, screenOnOffOptions,
+ List.of(greenReceiver, blueReceiver), false));
+ verifyPendingRecords(greenQueue, List.of(screenOn));
+ verifyPendingRecords(redQueue, List.of(screenOff));
+ verifyPendingRecords(blueQueue, List.of(screenOn));
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @SuppressWarnings("GuardedBy")
+ @Test
+ public void testDeliveryGroupPolicy_prioritized_diffReceivers_changeIdDisabled() {
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE),
+ eq(getUidForPackage(PACKAGE_GREEN)));
+
+ final Intent screenOn = new Intent(Intent.ACTION_SCREEN_ON);
+ final Intent screenOff = new Intent(Intent.ACTION_SCREEN_OFF);
+ final BroadcastOptions screenOnOffOptions = BroadcastOptions.makeBasic()
+ .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
+ .setDeliveryGroupMatchingKey("screenOnOff", Intent.ACTION_SCREEN_ON);
+
+ final Object greenReceiver = withPriority(
+ makeManifestReceiver(PACKAGE_GREEN, CLASS_GREEN), 10);
+ final Object redReceiver = withPriority(
+ makeManifestReceiver(PACKAGE_RED, CLASS_RED), 5);
+ final Object blueReceiver = withPriority(
+ makeManifestReceiver(PACKAGE_BLUE, CLASS_BLUE), 0);
+
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOn, screenOnOffOptions,
+ List.of(greenReceiver, blueReceiver), false));
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOff, screenOnOffOptions,
+ List.of(greenReceiver, redReceiver, blueReceiver), false));
+ final BroadcastProcessQueue greenQueue = mImpl.getProcessQueue(PACKAGE_GREEN,
+ getUidForPackage(PACKAGE_GREEN));
+ final BroadcastProcessQueue redQueue = mImpl.getProcessQueue(PACKAGE_RED,
+ getUidForPackage(PACKAGE_RED));
+ final BroadcastProcessQueue blueQueue = mImpl.getProcessQueue(PACKAGE_BLUE,
+ getUidForPackage(PACKAGE_BLUE));
+ verifyPendingRecords(greenQueue, List.of(screenOff));
+ verifyPendingRecords(redQueue, List.of(screenOff));
+ verifyPendingRecords(blueQueue, List.of(screenOff));
+
+ assertTrue(greenQueue.isEmpty());
+ assertTrue(redQueue.isEmpty());
+ assertTrue(blueQueue.isEmpty());
+
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOff, screenOnOffOptions,
+ List.of(greenReceiver, redReceiver, blueReceiver), false));
+ mImpl.enqueueBroadcastLocked(makeBroadcastRecord(screenOn, screenOnOffOptions,
+ List.of(greenReceiver, blueReceiver), false));
verifyPendingRecords(greenQueue, List.of(screenOff, screenOn));
verifyPendingRecords(redQueue, List.of(screenOff));
verifyPendingRecords(blueQueue, List.of(screenOff, screenOn));
@@ -1569,8 +1723,9 @@ public final class BroadcastQueueModernImplTest extends BaseBroadcastQueueTest {
verifyPendingRecords(redQueue, List.of(userPresent, timeTick));
}
+ @DisableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
- public void testDeliveryDeferredForCached() throws Exception {
+ public void testDeliveryDeferredForCached_flagDisabled() throws Exception {
final ProcessRecord greenProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_GREEN));
final ProcessRecord redProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_RED));
@@ -1664,8 +1819,217 @@ public final class BroadcastQueueModernImplTest extends BaseBroadcastQueueTest {
}, false /* andRemove */);
}
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @SuppressWarnings("GuardedBy")
+ @Test
+ public void testDeliveryDeferredForCached_changeIdDisabled() throws Exception {
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE),
+ eq(getUidForPackage(PACKAGE_GREEN)));
+
+ final ProcessRecord greenProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_GREEN));
+ final ProcessRecord redProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_RED));
+
+ final Intent timeTick = new Intent(Intent.ACTION_TIME_TICK);
+ final BroadcastRecord timeTickRecord = makeBroadcastRecord(timeTick,
+ List.of(makeRegisteredReceiver(greenProcess, 0)));
+
+ final Intent batteryChanged = new Intent(Intent.ACTION_BATTERY_CHANGED);
+ final BroadcastOptions optionsBatteryChanged =
+ BroadcastOptions.makeWithDeferUntilActive(true);
+ final BroadcastRecord batteryChangedRecord = makeBroadcastRecord(batteryChanged,
+ optionsBatteryChanged,
+ List.of(makeRegisteredReceiver(greenProcess, 10),
+ makeRegisteredReceiver(redProcess, 0)),
+ false /* ordered */);
+
+ mImpl.enqueueBroadcastLocked(timeTickRecord);
+ mImpl.enqueueBroadcastLocked(batteryChangedRecord);
+
+ final BroadcastProcessQueue greenQueue = mImpl.getProcessQueue(PACKAGE_GREEN,
+ getUidForPackage(PACKAGE_GREEN));
+ final BroadcastProcessQueue redQueue = mImpl.getProcessQueue(PACKAGE_RED,
+ getUidForPackage(PACKAGE_RED));
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, greenQueue.getRunnableAtReason());
+ assertFalse(greenQueue.shouldBeDeferred());
+ assertEquals(BroadcastProcessQueue.REASON_BLOCKED, redQueue.getRunnableAtReason());
+ assertFalse(redQueue.shouldBeDeferred());
+
+ // Simulate process state change
+ greenQueue.setProcessAndUidState(greenProcess, false /* uidForeground */,
+ true /* processFreezable */);
+ greenQueue.updateDeferredStates(mImpl.mBroadcastConsumerDeferApply,
+ mImpl.mBroadcastConsumerDeferClear);
+
+ assertEquals(BroadcastProcessQueue.REASON_CACHED, greenQueue.getRunnableAtReason());
+ assertTrue(greenQueue.shouldBeDeferred());
+ // Once the broadcasts to green process are deferred, broadcasts to red process
+ // shouldn't be blocked anymore.
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, redQueue.getRunnableAtReason());
+ assertFalse(redQueue.shouldBeDeferred());
+
+ // All broadcasts to green process should be deferred.
+ greenQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_DEFERRED, r.getDeliveryState(i));
+ }, false /* andRemove */);
+ redQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_PENDING, r.getDeliveryState(i));
+ }, false /* andRemove */);
+
+ final Intent packageChanged = new Intent(Intent.ACTION_PACKAGE_CHANGED);
+ final BroadcastRecord packageChangedRecord = makeBroadcastRecord(packageChanged,
+ List.of(makeRegisteredReceiver(greenProcess, 0)));
+ mImpl.enqueueBroadcastLocked(packageChangedRecord);
+
+ assertEquals(BroadcastProcessQueue.REASON_CACHED, greenQueue.getRunnableAtReason());
+ assertTrue(greenQueue.shouldBeDeferred());
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, redQueue.getRunnableAtReason());
+ assertFalse(redQueue.shouldBeDeferred());
+
+ // All broadcasts to the green process, including the newly enqueued one, should be
+ // deferred.
+ greenQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_DEFERRED, r.getDeliveryState(i));
+ }, false /* andRemove */);
+ redQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_PENDING, r.getDeliveryState(i));
+ }, false /* andRemove */);
+
+ // Simulate process state change
+ greenQueue.setProcessAndUidState(greenProcess, false /* uidForeground */,
+ false /* processFreezable */);
+ greenQueue.updateDeferredStates(mImpl.mBroadcastConsumerDeferApply,
+ mImpl.mBroadcastConsumerDeferClear);
+
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, greenQueue.getRunnableAtReason());
+ assertFalse(greenQueue.shouldBeDeferred());
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, redQueue.getRunnableAtReason());
+ assertFalse(redQueue.shouldBeDeferred());
+
+ greenQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_PENDING, r.getDeliveryState(i));
+ }, false /* andRemove */);
+ redQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_PENDING, r.getDeliveryState(i));
+ }, false /* andRemove */);
+ }
+
+ @DisableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @SuppressWarnings("GuardedBy")
+ @Test
+ public void testDeliveryDeferredForCached_withInfiniteDeferred_flagDisabled() throws Exception {
+ final ProcessRecord greenProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_GREEN));
+ final ProcessRecord redProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_RED));
+
+ final Intent timeTick = new Intent(Intent.ACTION_TIME_TICK);
+ final BroadcastOptions optionsTimeTick = BroadcastOptions.makeWithDeferUntilActive(true);
+ final BroadcastRecord timeTickRecord = makeBroadcastRecord(timeTick, optionsTimeTick,
+ List.of(makeRegisteredReceiver(greenProcess, 0)), false /* ordered */);
+
+ final Intent batteryChanged = new Intent(Intent.ACTION_BATTERY_CHANGED);
+ final BroadcastOptions optionsBatteryChanged =
+ BroadcastOptions.makeWithDeferUntilActive(true);
+ final BroadcastRecord batteryChangedRecord = makeBroadcastRecord(batteryChanged,
+ optionsBatteryChanged,
+ List.of(makeRegisteredReceiver(greenProcess, 10),
+ makeRegisteredReceiver(redProcess, 0)),
+ false /* ordered */);
+
+ mImpl.enqueueBroadcastLocked(timeTickRecord);
+ mImpl.enqueueBroadcastLocked(batteryChangedRecord);
+
+ final BroadcastProcessQueue greenQueue = mImpl.getProcessQueue(PACKAGE_GREEN,
+ getUidForPackage(PACKAGE_GREEN));
+ final BroadcastProcessQueue redQueue = mImpl.getProcessQueue(PACKAGE_RED,
+ getUidForPackage(PACKAGE_RED));
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, greenQueue.getRunnableAtReason());
+ assertFalse(greenQueue.shouldBeDeferred());
+ assertEquals(BroadcastProcessQueue.REASON_BLOCKED, redQueue.getRunnableAtReason());
+ assertFalse(redQueue.shouldBeDeferred());
+
+ // Simulate process state change
+ greenQueue.setProcessAndUidState(greenProcess, false /* uidForeground */,
+ true /* processFreezable */);
+ greenQueue.updateDeferredStates(mImpl.mBroadcastConsumerDeferApply,
+ mImpl.mBroadcastConsumerDeferClear);
+
+ assertEquals(BroadcastProcessQueue.REASON_CACHED_INFINITE_DEFER,
+ greenQueue.getRunnableAtReason());
+ assertTrue(greenQueue.shouldBeDeferred());
+ // Once the broadcasts to green process are deferred, broadcasts to red process
+ // shouldn't be blocked anymore.
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, redQueue.getRunnableAtReason());
+ assertFalse(redQueue.shouldBeDeferred());
+
+ // All broadcasts to green process should be deferred.
+ greenQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_DEFERRED, r.getDeliveryState(i));
+ }, false /* andRemove */);
+ redQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_PENDING, r.getDeliveryState(i));
+ }, false /* andRemove */);
+
+ final Intent packageChanged = new Intent(Intent.ACTION_PACKAGE_CHANGED);
+ final BroadcastOptions optionsPackageChanged =
+ BroadcastOptions.makeWithDeferUntilActive(true);
+ final BroadcastRecord packageChangedRecord = makeBroadcastRecord(packageChanged,
+ optionsPackageChanged,
+ List.of(makeRegisteredReceiver(greenProcess, 0)), false /* ordered */);
+ mImpl.enqueueBroadcastLocked(packageChangedRecord);
+
+ assertEquals(BroadcastProcessQueue.REASON_CACHED_INFINITE_DEFER,
+ greenQueue.getRunnableAtReason());
+ assertTrue(greenQueue.shouldBeDeferred());
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, redQueue.getRunnableAtReason());
+ assertFalse(redQueue.shouldBeDeferred());
+
+ // All broadcasts to the green process, including the newly enqueued one, should be
+ // deferred.
+ greenQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_DEFERRED, r.getDeliveryState(i));
+ }, false /* andRemove */);
+ redQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_PENDING, r.getDeliveryState(i));
+ }, false /* andRemove */);
+
+ // Simulate process state change
+ greenQueue.setProcessAndUidState(greenProcess, false /* uidForeground */,
+ false /* processFreezable */);
+ greenQueue.updateDeferredStates(mImpl.mBroadcastConsumerDeferApply,
+ mImpl.mBroadcastConsumerDeferClear);
+
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, greenQueue.getRunnableAtReason());
+ assertFalse(greenQueue.shouldBeDeferred());
+ assertEquals(BroadcastProcessQueue.REASON_NORMAL, redQueue.getRunnableAtReason());
+ assertFalse(redQueue.shouldBeDeferred());
+
+ greenQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_PENDING, r.getDeliveryState(i));
+ }, false /* andRemove */);
+ redQueue.forEachMatchingBroadcast(BROADCAST_PREDICATE_ANY, (r, i) -> {
+ assertEquals("Unexpected state for " + r,
+ BroadcastRecord.DELIVERY_PENDING, r.getDeliveryState(i));
+ }, false /* andRemove */);
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
- public void testDeliveryDeferredForCached_withInfiniteDeferred() throws Exception {
+ public void testDeliveryDeferredForCached_withInfiniteDeferred_changeIdDisabled()
+ throws Exception {
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE),
+ eq(getUidForPackage(PACKAGE_GREEN)));
final ProcessRecord greenProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_GREEN));
final ProcessRecord redProcess = makeProcessRecord(makeApplicationInfo(PACKAGE_RED));
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueTest.java b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueTest.java
index 3aaf2e5c61a6..eab5ce3cee2f 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastQueueTest.java
@@ -21,6 +21,7 @@ import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_FINISH_RECEIVER
import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_START_RECEIVER;
import static android.os.UserHandle.USER_SYSTEM;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
import static com.android.server.am.ActivityManagerDebugConfig.LOG_WRITER_INFO;
import static com.android.server.am.BroadcastProcessQueue.reasonToString;
import static com.android.server.am.BroadcastRecord.deliveryStateToString;
@@ -45,7 +46,6 @@ import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -77,6 +77,8 @@ import android.os.IBinder;
import android.os.PowerExemptionManager;
import android.os.SystemClock;
import android.os.UserHandle;
+import android.platform.test.annotations.DisableFlags;
+import android.platform.test.annotations.EnableFlags;
import android.platform.test.annotations.RequiresFlagsEnabled;
import android.util.ArrayMap;
import android.util.Log;
@@ -446,7 +448,8 @@ public class BroadcastQueueTest extends BaseBroadcastQueueTest {
callerApp.getPid(), callerApp.info.uid, false, null, null, null, null,
AppOpsManager.OP_NONE, options, receivers, callerApp, resultTo,
Activity.RESULT_OK, null, resultExtras, ordered, false, false, userId,
- BackgroundStartPrivileges.NONE, false, null, PROCESS_STATE_UNKNOWN);
+ BackgroundStartPrivileges.NONE, false, null, PROCESS_STATE_UNKNOWN,
+ mPlatformCompat);
}
private void assertHealth() {
@@ -1495,7 +1498,7 @@ public class BroadcastQueueTest extends BaseBroadcastQueueTest {
null, null, null, null, AppOpsManager.OP_NONE, BroadcastOptions.makeBasic(),
List.of(makeManifestReceiver(PACKAGE_GREEN, CLASS_GREEN)), null, null,
Activity.RESULT_OK, null, null, false, false, false, UserHandle.USER_SYSTEM,
- backgroundStartPrivileges, false, null, PROCESS_STATE_UNKNOWN);
+ backgroundStartPrivileges, false, null, PROCESS_STATE_UNKNOWN, mPlatformCompat);
enqueueBroadcast(r);
waitForIdle();
@@ -1550,8 +1553,9 @@ public class BroadcastQueueTest extends BaseBroadcastQueueTest {
/**
* Verify that when dispatching we respect tranches of priority.
*/
+ @DisableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
- public void testPriority() throws Exception {
+ public void testPriority_flagDisabled() throws Exception {
final ProcessRecord callerApp = makeActiveProcessRecord(PACKAGE_RED);
final ProcessRecord receiverBlueApp = makeActiveProcessRecord(PACKAGE_BLUE);
final ProcessRecord receiverGreenApp = makeActiveProcessRecord(PACKAGE_GREEN);
@@ -1594,6 +1598,104 @@ public class BroadcastQueueTest extends BaseBroadcastQueueTest {
}
/**
+ * Verify that when dispatching we respect tranches of priority.
+ */
+ @Test
+ public void testOrdered_withPriorities() throws Exception {
+ final ProcessRecord callerApp = makeActiveProcessRecord(PACKAGE_RED);
+ final ProcessRecord receiverBlueApp = makeActiveProcessRecord(PACKAGE_BLUE);
+ final ProcessRecord receiverGreenApp = makeActiveProcessRecord(PACKAGE_GREEN);
+ final ProcessRecord receiverYellowApp = makeActiveProcessRecord(PACKAGE_YELLOW);
+
+ // Enqueue a normal broadcast that will go to several processes, and
+ // then enqueue a foreground broadcast that risks reordering
+ final Intent timezone = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
+ final Intent airplane = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
+ airplane.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+ final IIntentReceiver orderedResultTo = mock(IIntentReceiver.class);
+ enqueueBroadcast(makeOrderedBroadcastRecord(timezone, callerApp,
+ List.of(makeRegisteredReceiver(receiverBlueApp, 10),
+ makeRegisteredReceiver(receiverGreenApp, 10),
+ makeManifestReceiver(PACKAGE_BLUE, CLASS_BLUE),
+ makeManifestReceiver(PACKAGE_YELLOW, CLASS_YELLOW),
+ makeRegisteredReceiver(receiverYellowApp, -10)),
+ orderedResultTo, null));
+ enqueueBroadcast(makeBroadcastRecord(airplane, callerApp,
+ List.of(makeRegisteredReceiver(receiverBlueApp))));
+ waitForIdle();
+
+ // Ignore the final foreground broadcast
+ mScheduledBroadcasts.remove(makeScheduledBroadcast(receiverBlueApp, airplane));
+ assertEquals(6, mScheduledBroadcasts.size());
+
+ // We're only concerned about enforcing ordering between tranches;
+ // within a tranche we're okay with reordering
+ assertEquals(
+ Set.of(makeScheduledBroadcast(receiverBlueApp, timezone),
+ makeScheduledBroadcast(receiverGreenApp, timezone)),
+ Set.of(mScheduledBroadcasts.remove(0),
+ mScheduledBroadcasts.remove(0)));
+ assertEquals(
+ Set.of(makeScheduledBroadcast(receiverBlueApp, timezone),
+ makeScheduledBroadcast(receiverYellowApp, timezone)),
+ Set.of(mScheduledBroadcasts.remove(0),
+ mScheduledBroadcasts.remove(0)));
+ assertEquals(
+ Set.of(makeScheduledBroadcast(receiverYellowApp, timezone)),
+ Set.of(mScheduledBroadcasts.remove(0)));
+ }
+
+ /**
+ * Verify that when dispatching we respect tranches of priority.
+ */
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testPriority_changeIdDisabled() throws Exception {
+ final ProcessRecord callerApp = makeActiveProcessRecord(PACKAGE_RED);
+ final ProcessRecord receiverBlueApp = makeActiveProcessRecord(PACKAGE_BLUE);
+ final ProcessRecord receiverGreenApp = makeActiveProcessRecord(PACKAGE_GREEN);
+ final ProcessRecord receiverYellowApp = makeActiveProcessRecord(PACKAGE_YELLOW);
+
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(receiverBlueApp.uid));
+
+ // Enqueue a normal broadcast that will go to several processes, and
+ // then enqueue a foreground broadcast that risks reordering
+ final Intent timezone = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
+ final Intent airplane = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
+ airplane.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+ enqueueBroadcast(makeBroadcastRecord(timezone, callerApp,
+ List.of(makeRegisteredReceiver(receiverBlueApp, 10),
+ makeRegisteredReceiver(receiverGreenApp, 10),
+ makeManifestReceiver(PACKAGE_BLUE, CLASS_BLUE),
+ makeManifestReceiver(PACKAGE_YELLOW, CLASS_YELLOW),
+ makeRegisteredReceiver(receiverYellowApp, -10))));
+ enqueueBroadcast(makeBroadcastRecord(airplane, callerApp,
+ List.of(makeRegisteredReceiver(receiverBlueApp))));
+ waitForIdle();
+
+ // Ignore the final foreground broadcast
+ mScheduledBroadcasts.remove(makeScheduledBroadcast(receiverBlueApp, airplane));
+ assertEquals(5, mScheduledBroadcasts.size());
+
+ // We're only concerned about enforcing ordering between tranches;
+ // within a tranche we're okay with reordering
+ assertEquals(
+ Set.of(makeScheduledBroadcast(receiverBlueApp, timezone),
+ makeScheduledBroadcast(receiverGreenApp, timezone)),
+ Set.of(mScheduledBroadcasts.remove(0),
+ mScheduledBroadcasts.remove(0)));
+ assertEquals(
+ Set.of(makeScheduledBroadcast(receiverBlueApp, timezone),
+ makeScheduledBroadcast(receiverYellowApp, timezone)),
+ Set.of(mScheduledBroadcasts.remove(0),
+ mScheduledBroadcasts.remove(0)));
+ assertEquals(
+ Set.of(makeScheduledBroadcast(receiverYellowApp, timezone)),
+ Set.of(mScheduledBroadcasts.remove(0)));
+ }
+
+ /**
* Verify prioritized receivers work as expected with deferrable broadcast - broadcast to
* app in cached state should be deferred and the rest should be delivered as per the priority
* order.
@@ -2305,8 +2407,35 @@ public class BroadcastQueueTest extends BaseBroadcastQueueTest {
.isLessThan(getReceiverScheduledTime(timeTickRecord, receiverBlue));
}
+ @DisableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testPrioritizedBroadcastDelivery_uidForeground_flagDisabled() throws Exception {
+ final ProcessRecord callerApp = makeActiveProcessRecord(PACKAGE_RED);
+ final ProcessRecord receiverBlueApp = makeActiveProcessRecord(PACKAGE_BLUE);
+ final ProcessRecord receiverGreenApp = makeActiveProcessRecord(PACKAGE_GREEN);
+
+ mUidObserver.onUidStateChanged(receiverGreenApp.info.uid,
+ ActivityManager.PROCESS_STATE_TOP, 0, ActivityManager.PROCESS_CAPABILITY_NONE);
+ waitForIdle();
+
+ final Intent timeTick = new Intent(Intent.ACTION_TIME_TICK);
+
+ final BroadcastFilter receiverBlue = makeRegisteredReceiver(receiverBlueApp, 10);
+ final BroadcastFilter receiverGreen = makeRegisteredReceiver(receiverGreenApp, 5);
+ final BroadcastRecord prioritizedRecord = makeBroadcastRecord(timeTick, callerApp,
+ List.of(receiverBlue, receiverGreen));
+
+ enqueueBroadcast(prioritizedRecord);
+
+ waitForIdle();
+ // Verify that uid foreground-ness does not impact that delivery of prioritized broadcast.
+ // That is, broadcast to receiverBlueApp gets scheduled before the one to receiverGreenApp.
+ assertThat(getReceiverScheduledTime(prioritizedRecord, receiverGreen))
+ .isGreaterThan(getReceiverScheduledTime(prioritizedRecord, receiverBlue));
+ }
+
@Test
- public void testPrioritizedBroadcastDelivery_uidForeground() throws Exception {
+ public void testOrderedBroadcastDelivery_uidForeground() throws Exception {
final ProcessRecord callerApp = makeActiveProcessRecord(PACKAGE_RED);
final ProcessRecord receiverBlueApp = makeActiveProcessRecord(PACKAGE_BLUE);
final ProcessRecord receiverGreenApp = makeActiveProcessRecord(PACKAGE_GREEN);
@@ -2319,6 +2448,37 @@ public class BroadcastQueueTest extends BaseBroadcastQueueTest {
final BroadcastFilter receiverBlue = makeRegisteredReceiver(receiverBlueApp, 10);
final BroadcastFilter receiverGreen = makeRegisteredReceiver(receiverGreenApp, 5);
+ final IIntentReceiver resultTo = mock(IIntentReceiver.class);
+ final BroadcastRecord prioritizedRecord = makeOrderedBroadcastRecord(timeTick, callerApp,
+ List.of(receiverBlue, receiverGreen), resultTo, null);
+
+ enqueueBroadcast(prioritizedRecord);
+
+ waitForIdle();
+ // Verify that uid foreground-ness does not impact that delivery of prioritized broadcast.
+ // That is, broadcast to receiverBlueApp gets scheduled before the one to receiverGreenApp.
+ assertThat(getReceiverScheduledTime(prioritizedRecord, receiverGreen))
+ .isGreaterThan(getReceiverScheduledTime(prioritizedRecord, receiverBlue));
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testPrioritizedBroadcastDelivery_uidForeground_changeIdDisabled() throws Exception {
+ final ProcessRecord callerApp = makeActiveProcessRecord(PACKAGE_RED);
+ final ProcessRecord receiverBlueApp = makeActiveProcessRecord(PACKAGE_BLUE);
+ final ProcessRecord receiverGreenApp = makeActiveProcessRecord(PACKAGE_GREEN);
+
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(receiverBlueApp.uid));
+
+ mUidObserver.onUidStateChanged(receiverGreenApp.info.uid,
+ ActivityManager.PROCESS_STATE_TOP, 0, ActivityManager.PROCESS_CAPABILITY_NONE);
+ waitForIdle();
+
+ final Intent timeTick = new Intent(Intent.ACTION_TIME_TICK);
+
+ final BroadcastFilter receiverBlue = makeRegisteredReceiver(receiverBlueApp, 10);
+ final BroadcastFilter receiverGreen = makeRegisteredReceiver(receiverGreenApp, 5);
final BroadcastRecord prioritizedRecord = makeBroadcastRecord(timeTick, callerApp,
List.of(receiverBlue, receiverGreen));
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastRecordTest.java b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastRecordTest.java
index 8cd0da721364..4a370a3cc431 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/BroadcastRecordTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/BroadcastRecordTest.java
@@ -18,6 +18,8 @@ package com.android.server.am;
import static android.app.ActivityManager.PROCESS_STATE_UNKNOWN;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
+import static com.android.server.am.BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE;
import static com.android.server.am.BroadcastRecord.DELIVERY_DEFERRED;
import static com.android.server.am.BroadcastRecord.DELIVERY_DELIVERED;
import static com.android.server.am.BroadcastRecord.DELIVERY_PENDING;
@@ -33,6 +35,8 @@ 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.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
import android.app.BackgroundStartPrivileges;
import android.app.BroadcastOptions;
@@ -46,11 +50,17 @@ import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.Process;
import android.os.UserHandle;
+import android.platform.test.annotations.DisableFlags;
+import android.platform.test.annotations.EnableFlags;
+import android.platform.test.flag.junit.SetFlagsRule;
import android.telephony.SubscriptionManager;
import androidx.test.filters.SmallTest;
+import com.android.server.compat.PlatformCompat;
+
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -73,6 +83,9 @@ import java.util.function.BiFunction;
public class BroadcastRecordTest {
private static final String TAG = "BroadcastRecordTest";
+ @Rule
+ public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
private static final int USER0 = UserHandle.USER_SYSTEM;
private static final String PACKAGE1 = "pkg1";
private static final String PACKAGE2 = "pkg2";
@@ -89,10 +102,14 @@ public class BroadcastRecordTest {
@Mock BroadcastQueue mQueue;
@Mock ProcessRecord mProcess;
+ @Mock PlatformCompat mPlatformCompat;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
+
+ doReturn(true).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), anyInt());
}
@Test
@@ -108,13 +125,13 @@ public class BroadcastRecordTest {
assertArrayEquals(new int[] {-1},
calculateBlockedUntilBeyondCount(List.of(
- createResolveInfo(PACKAGE1, getAppId(1), 0)), false));
+ createResolveInfo(PACKAGE1, getAppId(1), 0)), false, mPlatformCompat));
assertArrayEquals(new int[] {-1},
calculateBlockedUntilBeyondCount(List.of(
- createResolveInfo(PACKAGE1, getAppId(1), -10)), false));
+ createResolveInfo(PACKAGE1, getAppId(1), -10)), false, mPlatformCompat));
assertArrayEquals(new int[] {-1},
calculateBlockedUntilBeyondCount(List.of(
- createResolveInfo(PACKAGE1, getAppId(1), 10)), false));
+ createResolveInfo(PACKAGE1, getAppId(1), 10)), false, mPlatformCompat));
}
@Test
@@ -128,18 +145,19 @@ public class BroadcastRecordTest {
createResolveInfo(PACKAGE2, getAppId(2), 10),
createResolveInfo(PACKAGE3, getAppId(3), 10))));
- assertArrayEquals(new int[] {-1,-1,-1},
+ assertArrayEquals(new int[] {-1, -1, -1},
calculateBlockedUntilBeyondCount(List.of(
createResolveInfo(PACKAGE1, getAppId(1), 0),
createResolveInfo(PACKAGE2, getAppId(2), 0),
- createResolveInfo(PACKAGE3, getAppId(3), 0)), false));
- assertArrayEquals(new int[] {-1,-1,-1},
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {-1, -1, -1},
calculateBlockedUntilBeyondCount(List.of(
createResolveInfo(PACKAGE1, getAppId(1), 10),
createResolveInfo(PACKAGE2, getAppId(2), 10),
- createResolveInfo(PACKAGE3, getAppId(3), 10)), false));
+ createResolveInfo(PACKAGE3, getAppId(3), 10)), false, mPlatformCompat));
}
+ @DisableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
@Test
public void testIsPrioritized_Yes() {
assertTrue(isPrioritized(List.of(
@@ -151,18 +169,203 @@ public class BroadcastRecordTest {
createResolveInfo(PACKAGE2, getAppId(2), 0),
createResolveInfo(PACKAGE3, getAppId(3), 0))));
- assertArrayEquals(new int[] {0,1,2},
+ assertArrayEquals(new int[] {0, 1, 2},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 0, 2, 3, 3},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 20),
+ createResolveInfo(PACKAGE2, getAppId(2), 20),
+ createResolveInfo(PACKAGE3, getAppId(3), 10),
+ createResolveInfo(PACKAGE3, getAppId(3), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testIsPrioritized_withDifferentPriorities() {
+ assertFalse(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10))));
+ assertFalse(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0))));
+
+ assertArrayEquals(new int[] {-1, -1, -1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {-1, -1, -1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 10),
+ createResolveInfo(PACKAGE3, getAppId(3), -10)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {-1, -1, -1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {-1, -1, -1, -1, -1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 20),
+ createResolveInfo(PACKAGE2, getAppId(2), 20),
+ createResolveInfo(PACKAGE3, getAppId(3), 10),
+ createResolveInfo(PACKAGE3, getAppId(3), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testIsPrioritized_withDifferentPriorities_withFirstUidChangeIdDisabled() {
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(getAppId(1)));
+
+ assertTrue(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10))));
+ assertTrue(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0))));
+
+ assertArrayEquals(new int[] {0, 1, 1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 0, 1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 10),
+ createResolveInfo(PACKAGE3, getAppId(3), -10)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 0, 1, 1, 1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 20),
+ createResolveInfo(PACKAGE2, getAppId(2), 20),
+ createResolveInfo(PACKAGE3, getAppId(3), 10),
+ createResolveInfo(PACKAGE3, getAppId(3), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testIsPrioritized_withDifferentPriorities_withLastUidChangeIdDisabled() {
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(getAppId(3)));
+
+ assertTrue(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10))));
+ assertTrue(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0))));
+
+ assertArrayEquals(new int[] {0, 0, 2},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 0, 1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 0, 2, 3, 3},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 20),
+ createResolveInfo(PACKAGE2, getAppId(2), 20),
+ createResolveInfo(PACKAGE3, getAppId(3), 10),
+ createResolveInfo(PACKAGE3, getAppId(3), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testIsPrioritized_withDifferentPriorities_withUidChangeIdDisabled() {
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(getAppId(2)));
+
+ assertTrue(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10))));
+ assertTrue(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0))));
+
+ assertArrayEquals(new int[] {0, 1, 2},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 1, 0},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 0, 2, 2, 2},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 20),
+ createResolveInfo(PACKAGE2, getAppId(2), 20),
+ createResolveInfo(PACKAGE3, getAppId(3), 10),
+ createResolveInfo(PACKAGE3, getAppId(3), 0),
+ createResolveInfo(PACKAGE3, getAppId(4), 0)), false, mPlatformCompat));
+ }
+
+ @EnableFlags(Flags.FLAG_LIMIT_PRIORITY_SCOPE)
+ @Test
+ public void testIsPrioritized_withDifferentPriorities_withMultipleUidChangeIdDisabled() {
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(getAppId(1)));
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(getAppId(2)));
+
+ assertTrue(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), -10))));
+ assertTrue(isPrioritized(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0))));
+
+ assertArrayEquals(new int[] {0, 1, 2},
calculateBlockedUntilBeyondCount(List.of(
createResolveInfo(PACKAGE1, getAppId(1), 10),
createResolveInfo(PACKAGE2, getAppId(2), 0),
- createResolveInfo(PACKAGE3, getAppId(3), -10)), false));
- assertArrayEquals(new int[] {0,0,2,3,3},
+ createResolveInfo(PACKAGE3, getAppId(3), -10)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 1, 1},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 10),
+ createResolveInfo(PACKAGE2, getAppId(2), 0),
+ createResolveInfo(PACKAGE3, getAppId(3), 0)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 0, 2, 2, 2},
calculateBlockedUntilBeyondCount(List.of(
createResolveInfo(PACKAGE1, getAppId(1), 20),
createResolveInfo(PACKAGE2, getAppId(2), 20),
createResolveInfo(PACKAGE3, getAppId(3), 10),
createResolveInfo(PACKAGE3, getAppId(3), 0),
- createResolveInfo(PACKAGE3, getAppId(3), 0)), false));
+ createResolveInfo(PACKAGE3, getAppId(4), 0)), false, mPlatformCompat));
+ assertArrayEquals(new int[] {0, 0, 1, 1, 3},
+ calculateBlockedUntilBeyondCount(List.of(
+ createResolveInfo(PACKAGE1, getAppId(1), 20),
+ createResolveInfo(PACKAGE2, getAppId(3), 20),
+ createResolveInfo(PACKAGE3, getAppId(3), 10),
+ createResolveInfo(PACKAGE3, getAppId(3), 0),
+ createResolveInfo(PACKAGE3, getAppId(2), 0)), false, mPlatformCompat));
}
@Test
@@ -602,6 +805,66 @@ public class BroadcastRecordTest {
assertTrue(record3.matchesDeliveryGroup(record1));
}
+ @Test
+ public void testCalculateChangeStateForReceivers() {
+ assertArrayEquals(new boolean[] {true, true, true}, calculateChangeState(
+ List.of(createResolveInfo(PACKAGE1, getAppId(1)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE3, getAppId(3)))));
+ assertArrayEquals(new boolean[] {true, true, true, true}, calculateChangeState(
+ List.of(createResolveInfo(PACKAGE1, getAppId(1)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE3, getAppId(3)))));
+
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(getAppId(1)));
+ assertArrayEquals(new boolean[] {false, true, true}, calculateChangeState(
+ List.of(createResolveInfo(PACKAGE1, getAppId(1)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE3, getAppId(3)))));
+ assertArrayEquals(new boolean[] {false, true, false, true}, calculateChangeState(
+ List.of(createResolveInfo(PACKAGE1, getAppId(1)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE2, getAppId(1)),
+ createResolveInfo(PACKAGE3, getAppId(3)))));
+
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(getAppId(2)));
+ assertArrayEquals(new boolean[] {false, false, true}, calculateChangeState(
+ List.of(createResolveInfo(PACKAGE1, getAppId(1)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE3, getAppId(3)))));
+ assertArrayEquals(new boolean[] {false, true, false, false, false, true},
+ calculateChangeState(
+ List.of(createResolveInfo(PACKAGE1, getAppId(1)),
+ createResolveInfo(PACKAGE3, getAppId(3)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE2, getAppId(1)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE3, getAppId(3)))));
+
+ doReturn(false).when(mPlatformCompat).isChangeEnabledByUidInternalNoLogging(
+ eq(BroadcastRecord.CHANGE_LIMIT_PRIORITY_SCOPE), eq(getAppId(3)));
+ assertArrayEquals(new boolean[] {false, false, false}, calculateChangeState(
+ List.of(createResolveInfo(PACKAGE1, getAppId(1)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE3, getAppId(3)))));
+ assertArrayEquals(new boolean[] {false, false, false, false, false, false},
+ calculateChangeState(
+ List.of(createResolveInfo(PACKAGE1, getAppId(1)),
+ createResolveInfo(PACKAGE3, getAppId(3)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE2, getAppId(1)),
+ createResolveInfo(PACKAGE2, getAppId(2)),
+ createResolveInfo(PACKAGE3, getAppId(3)))));
+ }
+
+ private boolean[] calculateChangeState(List<Object> receivers) {
+ return BroadcastRecord.calculateChangeStateForReceivers(receivers,
+ CHANGE_LIMIT_PRIORITY_SCOPE, mPlatformCompat);
+ }
+
private static void cleanupDisabledPackageReceivers(BroadcastRecord record,
String packageName, int userId) {
record.cleanupDisabledPackageReceiversLocked(packageName, null /* filterByClasses */,
@@ -753,16 +1016,17 @@ public class BroadcastRecordTest {
BackgroundStartPrivileges.NONE,
false /* timeoutExempt */,
filterExtrasForReceiver,
- PROCESS_STATE_UNKNOWN);
+ PROCESS_STATE_UNKNOWN,
+ mPlatformCompat);
}
private static int getAppId(int i) {
return Process.FIRST_APPLICATION_UID + i;
}
- private static boolean isPrioritized(List<Object> receivers) {
+ private boolean isPrioritized(List<Object> receivers) {
return BroadcastRecord.isPrioritized(
- calculateBlockedUntilBeyondCount(receivers, false), false);
+ calculateBlockedUntilBeyondCount(receivers, false, mPlatformCompat), false);
}
private static void assertBlocked(BroadcastRecord r, boolean... blocked) {
diff --git a/services/tests/servicestests/AndroidManifest.xml b/services/tests/servicestests/AndroidManifest.xml
index c645c0852f1b..9b7bbe04132c 100644
--- a/services/tests/servicestests/AndroidManifest.xml
+++ b/services/tests/servicestests/AndroidManifest.xml
@@ -114,6 +114,7 @@
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.CREATE_VIRTUAL_DEVICE" />
+ <uses-permission android:name="android.permission.MANAGE_KEY_GESTURES" />
<queries>
<package android:name="com.android.servicestests.apps.suspendtestapp" />
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/magnification/MagnificationControllerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/magnification/MagnificationControllerTest.java
index 8164ef9314d9..f0d3456a39de 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/magnification/MagnificationControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/magnification/MagnificationControllerTest.java
@@ -19,9 +19,13 @@ package com.android.server.accessibility.magnification;
import static android.provider.Settings.Secure.ACCESSIBILITY_MAGNIFICATION_MODE_FULLSCREEN;
import static android.provider.Settings.Secure.ACCESSIBILITY_MAGNIFICATION_MODE_WINDOW;
+import static com.android.internal.accessibility.common.MagnificationConstants.SCALE_MAX_VALUE;
+import static com.android.internal.accessibility.common.MagnificationConstants.SCALE_MIN_VALUE;
import static com.android.server.accessibility.AccessibilityManagerService.MAGNIFICATION_GESTURE_HANDLER_ID;
import static com.android.server.wm.WindowManagerInternal.AccessibilityControllerInternal.UiChangesForAccessibilityCallbacks;
+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.assertTrue;
@@ -660,6 +664,90 @@ public class MagnificationControllerTest {
}
@Test
+ public void scaleMagnificationByStep_fullscreenMode_stepInAndOut() throws RemoteException {
+ setMagnificationEnabled(MODE_FULLSCREEN);
+ mMagnificationController.onPerformScaleAction(TEST_DISPLAY, 1.0f, false);
+ reset(mScreenMagnificationController);
+
+ // Verify the zoom scale factor increases by
+ // {@code MagnificationController.DefaultMagnificationScaleStepProvider
+ // .ZOOM_STEP_SCALE_FACTOR} and the center coordinates are
+ // unchanged (Float.NaN as values denotes unchanged center).
+ mMagnificationController.scaleMagnificationByStep(TEST_DISPLAY,
+ MagnificationController.ZOOM_DIRECTION_IN);
+ verify(mScreenMagnificationController).setScaleAndCenter(eq(TEST_DISPLAY),
+ eq(MagnificationController
+ .DefaultMagnificationScaleStepProvider.ZOOM_STEP_SCALE_FACTOR),
+ eq(Float.NaN), eq(Float.NaN), anyBoolean(), anyInt());
+
+ mMagnificationController.scaleMagnificationByStep(TEST_DISPLAY,
+ MagnificationController.ZOOM_DIRECTION_OUT);
+ verify(mScreenMagnificationController).setScaleAndCenter(eq(TEST_DISPLAY),
+ eq(SCALE_MIN_VALUE), eq(Float.NaN), eq(Float.NaN), anyBoolean(), anyInt());
+ }
+
+ @Test
+ public void scaleMagnificationByStep_testMaxScaling() throws RemoteException {
+ setMagnificationEnabled(MODE_FULLSCREEN);
+ mMagnificationController.onPerformScaleAction(TEST_DISPLAY, SCALE_MIN_VALUE, false);
+ reset(mScreenMagnificationController);
+
+ float currentScale = mScreenMagnificationController.getScale(TEST_DISPLAY);
+ while (currentScale < SCALE_MAX_VALUE) {
+ assertThat(mMagnificationController.scaleMagnificationByStep(TEST_DISPLAY,
+ MagnificationController.ZOOM_DIRECTION_IN)).isTrue();
+ final float nextScale = mScreenMagnificationController.getScale(TEST_DISPLAY);
+ assertThat(nextScale).isGreaterThan(currentScale);
+ currentScale = nextScale;
+ }
+
+ assertThat(currentScale).isEqualTo(SCALE_MAX_VALUE);
+ assertThat(mMagnificationController.scaleMagnificationByStep(TEST_DISPLAY,
+ MagnificationController.ZOOM_DIRECTION_IN)).isFalse();
+ }
+
+ @Test
+ public void scaleMagnificationByStep_testMinScaling() throws RemoteException {
+ setMagnificationEnabled(MODE_FULLSCREEN);
+ mMagnificationController.onPerformScaleAction(TEST_DISPLAY, SCALE_MAX_VALUE, false);
+ reset(mScreenMagnificationController);
+
+ float currentScale = mScreenMagnificationController.getScale(TEST_DISPLAY);
+ while (currentScale > SCALE_MIN_VALUE) {
+ assertThat(mMagnificationController.scaleMagnificationByStep(TEST_DISPLAY,
+ MagnificationController.ZOOM_DIRECTION_OUT)).isTrue();
+ final float nextScale = mScreenMagnificationController.getScale(TEST_DISPLAY);
+ assertThat(nextScale).isLessThan(currentScale);
+ currentScale = nextScale;
+ }
+
+ assertThat(currentScale).isEqualTo(SCALE_MIN_VALUE);
+ assertThat(mMagnificationController.scaleMagnificationByStep(TEST_DISPLAY,
+ MagnificationController.ZOOM_DIRECTION_OUT)).isFalse();
+ }
+
+ @Test
+ public void scaleMagnificationByStep_windowedMode_stepInAndOut() throws RemoteException {
+ setMagnificationEnabled(MODE_WINDOW);
+ mMagnificationController.onPerformScaleAction(TEST_DISPLAY, SCALE_MIN_VALUE, false);
+ reset(mMagnificationConnectionManager);
+
+ // Verify the zoom scale factor increases by
+ // {@code MagnificationController.DefaultMagnificationScaleStepProvider
+ // .ZOOM_STEP_SCALE_FACTOR}.
+ mMagnificationController.scaleMagnificationByStep(TEST_DISPLAY,
+ MagnificationController.ZOOM_DIRECTION_IN);
+ verify(mMagnificationConnectionManager).setScale(eq(TEST_DISPLAY),
+ eq(MagnificationController
+ .DefaultMagnificationScaleStepProvider.ZOOM_STEP_SCALE_FACTOR));
+
+ mMagnificationController.scaleMagnificationByStep(TEST_DISPLAY,
+ MagnificationController.ZOOM_DIRECTION_OUT);
+ verify(mMagnificationConnectionManager).setScale(eq(TEST_DISPLAY),
+ eq(SCALE_MIN_VALUE));
+ }
+
+ @Test
public void enableWindowMode_notifyMagnificationChanged() throws RemoteException {
setMagnificationEnabled(MODE_WINDOW);
diff --git a/services/tests/servicestests/src/com/android/server/adaptiveauth/OWNERS b/services/tests/servicestests/src/com/android/server/adaptiveauth/OWNERS
deleted file mode 100644
index 0218a7835586..000000000000
--- a/services/tests/servicestests/src/com/android/server/adaptiveauth/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-include /services/core/java/com/android/server/adaptiveauth/OWNERS \ No newline at end of file
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
index bc410d9168a9..88829c1a99b3 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
@@ -62,6 +62,7 @@ import android.hardware.biometrics.BiometricAuthenticator;
import android.hardware.biometrics.BiometricConstants;
import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
+import android.hardware.biometrics.BiometricStateListener;
import android.hardware.biometrics.Flags;
import android.hardware.biometrics.IBiometricAuthenticator;
import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
@@ -70,8 +71,16 @@ import android.hardware.biometrics.IBiometricService;
import android.hardware.biometrics.IBiometricServiceReceiver;
import android.hardware.biometrics.IBiometricSysuiReceiver;
import android.hardware.biometrics.PromptInfo;
+import android.hardware.biometrics.SensorProperties;
import android.hardware.display.DisplayManagerGlobal;
+import android.hardware.face.FaceManager;
+import android.hardware.face.FaceSensorProperties;
+import android.hardware.face.FaceSensorPropertiesInternal;
+import android.hardware.face.IFaceAuthenticatorsRegisteredCallback;
import android.hardware.fingerprint.FingerprintManager;
+import android.hardware.fingerprint.FingerprintSensorProperties;
+import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
+import android.hardware.fingerprint.IFingerprintAuthenticatorsRegisteredCallback;
import android.hardware.keymaster.HardwareAuthenticatorType;
import android.os.Binder;
import android.os.Handler;
@@ -84,6 +93,7 @@ import android.platform.test.annotations.RequiresFlagsEnabled;
import android.platform.test.flag.junit.CheckFlagsRule;
import android.platform.test.flag.junit.DeviceFlagsValueProvider;
import android.platform.test.flag.junit.SetFlagsRule;
+import android.provider.Settings;
import android.security.GateKeeper;
import android.security.KeyStoreAuthorization;
import android.service.gatekeeper.IGateKeeperService;
@@ -93,6 +103,7 @@ import android.view.Display;
import android.view.DisplayInfo;
import android.view.WindowManager;
+import androidx.test.core.app.ApplicationProvider;
import androidx.test.filters.SmallTest;
import com.android.internal.R;
@@ -111,6 +122,7 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@@ -144,6 +156,27 @@ public class BiometricServiceTest {
private static final int SENSOR_ID_FINGERPRINT = 0;
private static final int SENSOR_ID_FACE = 1;
+ private final ArgumentCaptor<IFingerprintAuthenticatorsRegisteredCallback.Stub>
+ mFingerprintAuthenticatorRegisteredCallbackCaptor = ArgumentCaptor.forClass(
+ IFingerprintAuthenticatorsRegisteredCallback.Stub.class);
+ private final ArgumentCaptor<IFaceAuthenticatorsRegisteredCallback.Stub>
+ mFaceAuthenticatorRegisteredCallbackCaptor = ArgumentCaptor.forClass(
+ IFaceAuthenticatorsRegisteredCallback.Stub.class);
+ private final ArgumentCaptor<BiometricStateListener> mBiometricStateListenerArgumentCaptor =
+ ArgumentCaptor.forClass(BiometricStateListener.class);
+ private final List<FingerprintSensorPropertiesInternal>
+ mFingerprintSensorPropertiesInternals = List.of(
+ new FingerprintSensorPropertiesInternal(SENSOR_ID_FINGERPRINT,
+ SensorProperties.STRENGTH_STRONG, 5 /* maxEnrollmentsPerUser */,
+ List.of(), FingerprintSensorProperties.TYPE_UNKNOWN,
+ true /* resetLockoutRequiresHardwareAuthToken */));
+ private final List<FaceSensorPropertiesInternal>
+ mFaceSensorPropertiesInternals = List.of(
+ new FaceSensorPropertiesInternal(SENSOR_ID_FACE,
+ SensorProperties.STRENGTH_STRONG, 5 /* maxEnrollmentsPerUser */,
+ List.of(), FaceSensorProperties.TYPE_UNKNOWN,
+ false /* supportsFaceDetection */, false /* supportsSelfIllumination */,
+ false /* resetLockoutRequiresChallenge */));
private BiometricService mBiometricService;
@@ -192,6 +225,10 @@ public class BiometricServiceTest {
@Mock
private BiometricNotificationLogger mNotificationLogger;
+ @Mock
+ private FingerprintManager mFingerprintManager;
+ @Mock
+ private FaceManager mFaceManager;
BiometricContextProvider mBiometricContextProvider;
@@ -1975,6 +2012,59 @@ public class BiometricServiceTest {
eq(hardwareAuthenticators));
}
+ @Test
+ public void testMandatoryBiometricsValue_whenParentProfileEnabled() throws RemoteException {
+ final Context context = ApplicationProvider.getApplicationContext();
+ final int profileParentId = context.getContentResolver().getUserId();
+ final int userId = profileParentId + 1;
+ final BiometricService.SettingObserver settingObserver =
+ new BiometricService.SettingObserver(
+ context, mBiometricHandlerProvider.getBiometricCallbackHandler(),
+ new ArrayList<>(), mUserManager, mFingerprintManager, mFaceManager);
+
+ verify(mFingerprintManager).addAuthenticatorsRegisteredCallback(
+ mFingerprintAuthenticatorRegisteredCallbackCaptor.capture());
+ verify(mFaceManager).addAuthenticatorsRegisteredCallback(
+ mFaceAuthenticatorRegisteredCallbackCaptor.capture());
+
+ mFingerprintAuthenticatorRegisteredCallbackCaptor.getValue().onAllAuthenticatorsRegistered(
+ mFingerprintSensorPropertiesInternals);
+ mFaceAuthenticatorRegisteredCallbackCaptor.getValue().onAllAuthenticatorsRegistered(
+ mFaceSensorPropertiesInternals);
+
+ verify(mFingerprintManager).registerBiometricStateListener(
+ mBiometricStateListenerArgumentCaptor.capture());
+
+ mBiometricStateListenerArgumentCaptor.getValue().onEnrollmentsChanged(userId,
+ SENSOR_ID_FINGERPRINT, true /* hasEnrollments */);
+
+ verify(mFaceManager).registerBiometricStateListener(
+ mBiometricStateListenerArgumentCaptor.capture());
+
+ mBiometricStateListenerArgumentCaptor.getValue().onEnrollmentsChanged(userId,
+ SENSOR_ID_FACE, true /* hasEnrollments */);
+
+ when(mUserManager.getProfileParent(userId)).thenReturn(new UserInfo(profileParentId,
+ "", 0));
+ when(mUserManager.getEnabledProfileIds(profileParentId)).thenReturn(new int[]{userId});
+
+ //Disable Identity Check for profile user
+ Settings.Secure.putIntForUser(context.getContentResolver(),
+ Settings.Secure.MANDATORY_BIOMETRICS, 0, userId);
+ Settings.Secure.putIntForUser(context.getContentResolver(),
+ Settings.Secure.MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED, 0,
+ userId);
+ //Enable Identity Check for parent user
+ Settings.Secure.putIntForUser(context.getContentResolver(),
+ Settings.Secure.MANDATORY_BIOMETRICS, 1, profileParentId);
+ Settings.Secure.putIntForUser(context.getContentResolver(),
+ Settings.Secure.MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED, 1,
+ profileParentId);
+
+ assertTrue(settingObserver.getMandatoryBiometricsEnabledAndRequirementsSatisfiedForUser(
+ userId));
+ }
+
// Helper methods
private int invokeCanAuthenticate(BiometricService service, int authenticators)
diff --git a/services/tests/servicestests/src/com/android/server/adaptiveauth/AdaptiveAuthServiceTest.java b/services/tests/servicestests/src/com/android/server/security/adaptiveauthentication/AdaptiveAuthenticationServiceTest.java
index d1806881ee37..154494a13072 100644
--- a/services/tests/servicestests/src/com/android/server/adaptiveauth/AdaptiveAuthServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/security/adaptiveauthentication/AdaptiveAuthenticationServiceTest.java
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-package com.android.server.adaptiveauth;
+package com.android.server.security.adaptiveauthentication;
import static android.adaptiveauth.Flags.FLAG_ENABLE_ADAPTIVE_AUTH;
import static android.adaptiveauth.Flags.FLAG_REPORT_BIOMETRIC_AUTH_ATTEMPTS;
import static android.security.Flags.FLAG_REPORT_PRIMARY_AUTH_ATTEMPTS;
import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_ADAPTIVE_AUTH_REQUEST;
-import static com.android.server.adaptiveauth.AdaptiveAuthService.MAX_ALLOWED_FAILED_AUTH_ATTEMPTS;
+import static com.android.server.security.adaptiveauthentication.AdaptiveAuthenticationService.MAX_ALLOWED_FAILED_AUTH_ATTEMPTS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeTrue;
@@ -66,12 +66,12 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
- * atest FrameworksServicesTests:AdaptiveAuthServiceTest
+ * atest FrameworksServicesTests:AdaptiveAuthenticationServiceTest
*/
@Presubmit
@SmallTest
@RunWith(AndroidJUnit4.class)
-public class AdaptiveAuthServiceTest {
+public class AdaptiveAuthenticationServiceTest {
@Rule
public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@@ -81,7 +81,7 @@ public class AdaptiveAuthServiceTest {
private static final int REASON_UNKNOWN = 0; // BiometricRequestConstants.RequestReason
private Context mContext;
- private AdaptiveAuthService mAdaptiveAuthService;
+ private AdaptiveAuthenticationService mAdaptiveAuthenticationService;
@Mock
LockPatternUtils mLockPatternUtils;
@@ -124,8 +124,9 @@ public class AdaptiveAuthServiceTest {
LocalServices.removeServiceForTest(UserManagerInternal.class);
LocalServices.addService(UserManagerInternal.class, mUserManager);
- mAdaptiveAuthService = new AdaptiveAuthService(mContext, mLockPatternUtils);
- mAdaptiveAuthService.init();
+ mAdaptiveAuthenticationService = new AdaptiveAuthenticationService(
+ mContext, mLockPatternUtils);
+ mAdaptiveAuthenticationService.init();
verify(mLockSettings).registerLockSettingsStateListener(
mLockSettingsStateListenerCaptor.capture());
@@ -317,13 +318,13 @@ public class AdaptiveAuthServiceTest {
private void verifyNotLockDevice(int expectedCntFailedAttempts, int userId) {
assertEquals(expectedCntFailedAttempts,
- mAdaptiveAuthService.mFailedAttemptsForUser.get(userId));
+ mAdaptiveAuthenticationService.mFailedAttemptsForUser.get(userId));
verify(mWindowManager, never()).lockNow();
}
private void verifyLockDevice(int userId) {
assertEquals(MAX_ALLOWED_FAILED_AUTH_ATTEMPTS,
- mAdaptiveAuthService.mFailedAttemptsForUser.get(userId));
+ mAdaptiveAuthenticationService.mFailedAttemptsForUser.get(userId));
verify(mLockPatternUtils).requireStrongAuth(
eq(SOME_AUTH_REQUIRED_AFTER_ADAPTIVE_AUTH_REQUEST), eq(userId));
// If userId is MANAGED_PROFILE_USER_ID, the StrongAuthFlag of its parent (PRIMARY_USER_ID)
diff --git a/services/tests/servicestests/src/com/android/server/security/adaptiveauthentication/OWNERS b/services/tests/servicestests/src/com/android/server/security/adaptiveauthentication/OWNERS
new file mode 100644
index 000000000000..bc8efa92c16f
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/security/adaptiveauthentication/OWNERS
@@ -0,0 +1 @@
+include /services/core/java/com/android/server/security/adaptiveauthentication/OWNERS \ No newline at end of file
diff --git a/services/tests/uiservicestests/src/com/android/server/UiServiceTestCase.java b/services/tests/uiservicestests/src/com/android/server/UiServiceTestCase.java
index c9d5241c57b7..b3ec2153542a 100644
--- a/services/tests/uiservicestests/src/com/android/server/UiServiceTestCase.java
+++ b/services/tests/uiservicestests/src/com/android/server/UiServiceTestCase.java
@@ -30,7 +30,6 @@ import android.testing.TestableContext;
import androidx.test.InstrumentationRegistry;
-import com.android.server.pm.UserManagerInternal;
import com.android.server.uri.UriGrantsManagerInternal;
import org.junit.After;
@@ -42,7 +41,6 @@ import org.mockito.MockitoAnnotations;
public class UiServiceTestCase {
@Mock protected PackageManagerInternal mPmi;
- @Mock protected UserManagerInternal mUmi;
@Mock protected UriGrantsManagerInternal mUgmInternal;
protected static final String PKG_N_MR1 = "com.example.n_mr1";
@@ -94,8 +92,6 @@ public class UiServiceTestCase {
}
});
- LocalServices.removeServiceForTest(UserManagerInternal.class);
- LocalServices.addService(UserManagerInternal.class, mUmi);
LocalServices.removeServiceForTest(UriGrantsManagerInternal.class);
LocalServices.addService(UriGrantsManagerInternal.class, mUgmInternal);
when(mUgmInternal.checkGrantUriPermission(
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java
index 38ff3a22022d..cc0286508cdc 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java
@@ -2410,11 +2410,13 @@ public class GroupHelperTest extends UiServiceTestCase {
NotificationChannel.NEWS_ID);
for (NotificationRecord record: notificationList) {
if (record.getChannel().getId().equals(channel1.getId())
+ && record.getNotification().isGroupChild()
&& record.getSbn().getId() % 2 == 0) {
record.updateNotificationChannel(socialChannel);
mGroupHelper.onChannelUpdated(record);
}
if (record.getChannel().getId().equals(channel1.getId())
+ && record.getNotification().isGroupChild()
&& record.getSbn().getId() % 2 != 0) {
record.updateNotificationChannel(newsChannel);
mGroupHelper.onChannelUpdated(record);
@@ -2474,7 +2476,8 @@ public class GroupHelperTest extends UiServiceTestCase {
NotificationChannel.SOCIAL_MEDIA_ID, NotificationChannel.SOCIAL_MEDIA_ID,
IMPORTANCE_DEFAULT);
for (NotificationRecord record: notificationList) {
- if (record.getChannel().getId().equals(channel1.getId())) {
+ if (record.getChannel().getId().equals(channel1.getId())
+ && record.getNotification().isGroupChild()) {
record.updateNotificationChannel(socialChannel);
mGroupHelper.onChannelUpdated(record);
}
@@ -2532,7 +2535,8 @@ public class GroupHelperTest extends UiServiceTestCase {
BASE_FLAGS, mSmallIcon, COLOR_DEFAULT, DEFAULT_VISIBILITY, DEFAULT_GROUP_ALERT,
NotificationChannel.SOCIAL_MEDIA_ID);
for (NotificationRecord record: notificationList) {
- if (record.getOriginalGroupKey().contains("testGrp")) {
+ if (record.getOriginalGroupKey().contains("testGrp")
+ && record.getNotification().isGroupChild()) {
record.updateNotificationChannel(socialChannel);
mGroupHelper.onChannelUpdated(record);
}
@@ -2631,7 +2635,8 @@ public class GroupHelperTest extends UiServiceTestCase {
BASE_FLAGS, mSmallIcon, COLOR_DEFAULT, DEFAULT_VISIBILITY, DEFAULT_GROUP_ALERT,
NotificationChannel.SOCIAL_MEDIA_ID);
for (NotificationRecord record: notificationList) {
- if (record.getOriginalGroupKey().contains("testGrp")) {
+ if (record.getOriginalGroupKey().contains("testGrp")
+ && record.getNotification().isGroupChild()) {
record.updateNotificationChannel(socialChannel);
mGroupHelper.onChannelUpdated(record);
}
@@ -2650,6 +2655,64 @@ public class GroupHelperTest extends UiServiceTestCase {
}
@Test
+ @EnableFlags({FLAG_NOTIFICATION_FORCE_GROUPING,
+ FLAG_NOTIFICATION_REGROUP_ON_CLASSIFICATION,
+ FLAG_NOTIFICATION_CLASSIFICATION})
+ public void testValidGroupsRegrouped_notificationBundledWhileEnqueued() {
+ // Check that valid group notifications are regrouped if classification is done
+ // before onNotificationPostedWithDelay (within DELAY_FOR_ASSISTANT_TIME)
+ final List<NotificationRecord> notificationList = new ArrayList<>();
+ final ArrayMap<String, NotificationRecord> summaryByGroup = new ArrayMap<>();
+ final String pkg = "package";
+
+ final int summaryId = 0;
+ final int numChildren = 3;
+ // Post a regular/valid group: summary + notifications
+ NotificationRecord summary = getNotificationRecord(pkg, summaryId,
+ String.valueOf(summaryId), UserHandle.SYSTEM, "testGrp", true);
+ notificationList.add(summary);
+ summaryByGroup.put(summary.getGroupKey(), summary);
+ for (int i = 0; i < numChildren; i++) {
+ NotificationRecord child = getNotificationRecord(pkg, i + 42, String.valueOf(i + 42),
+ UserHandle.SYSTEM, "testGrp", false);
+ notificationList.add(child);
+ }
+
+ // Classify/bundle child notifications. Don't call onChannelUpdated,
+ // adjustments applied while enqueued will use NotificationAdjustmentExtractor.
+ final NotificationChannel socialChannel = new NotificationChannel(
+ NotificationChannel.SOCIAL_MEDIA_ID, NotificationChannel.SOCIAL_MEDIA_ID,
+ IMPORTANCE_DEFAULT);
+ final String expectedGroupKey_social = GroupHelper.getFullAggregateGroupKey(pkg,
+ AGGREGATE_GROUP_KEY + "SocialSection", UserHandle.SYSTEM.getIdentifier());
+ final NotificationAttributes expectedSummaryAttr_social = new NotificationAttributes(
+ BASE_FLAGS, mSmallIcon, COLOR_DEFAULT, DEFAULT_VISIBILITY, DEFAULT_GROUP_ALERT,
+ NotificationChannel.SOCIAL_MEDIA_ID);
+ for (NotificationRecord record: notificationList) {
+ if (record.getOriginalGroupKey().contains("testGrp")
+ && record.getNotification().isGroupChild()) {
+ record.updateNotificationChannel(socialChannel);
+ }
+ }
+
+ // Check that notifications are forced grouped and app-provided summaries are canceled
+ for (NotificationRecord record: notificationList) {
+ mGroupHelper.onNotificationPostedWithDelay(record, notificationList, summaryByGroup);
+ }
+
+ verify(mCallback, times(1)).addAutoGroupSummary(anyInt(), eq(pkg), anyString(),
+ eq(expectedGroupKey_social), anyInt(), eq(expectedSummaryAttr_social));
+ verify(mCallback, times(numChildren)).addAutoGroup(anyString(), eq(expectedGroupKey_social),
+ eq(true));
+ verify(mCallback, never()).removeAutoGroup(anyString());
+ verify(mCallback, never()).removeAutoGroupSummary(anyInt(), anyString(), anyString());
+ verify(mCallback, times(numChildren - 1)).updateAutogroupSummary(anyInt(), anyString(),
+ anyString(), any());
+ verify(mCallback, times(numChildren)).removeAppProvidedSummaryOnClassification(anyString(),
+ anyString());
+ }
+
+ @Test
@EnableFlags(FLAG_NOTIFICATION_FORCE_GROUPING)
public void testMoveAggregateGroups_updateChannel_groupsUngrouped() {
final String pkg = "package";
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
index 48bc9d7c51a1..e5c42082ab97 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
@@ -1484,7 +1484,6 @@ public class ManagedServicesTest extends UiServiceTestCase {
assertTrue(componentsToUnbind.get(0).contains(ComponentName.unflattenFromString("c/c")));
}
- @SuppressWarnings("GuardedBy")
@Test
public void populateComponentsToBind() {
ManagedServices service = new TestManagedServices(getContext(), mLock, mUserProfiles, mIpm,
@@ -1508,8 +1507,7 @@ public class ManagedServicesTest extends UiServiceTestCase {
SparseArray<Set<ComponentName>> componentsToBind = new SparseArray<>();
- service.populateComponentsToBind(componentsToBind, users, approvedComponentsByUser,
- /* isVisibleBackgroundUser= */ false);
+ service.populateComponentsToBind(componentsToBind, users, approvedComponentsByUser);
assertEquals(2, componentsToBind.size());
assertEquals(1, componentsToBind.get(0).size());
@@ -1519,33 +1517,6 @@ public class ManagedServicesTest extends UiServiceTestCase {
assertTrue(componentsToBind.get(10).contains(ComponentName.unflattenFromString("c/c")));
}
- @SuppressWarnings("GuardedBy")
- @Test
- public void populateComponentsToBind_isVisibleBackgroundUser_addComponentsToBindButNotAddToEnabledComponent() {
- ManagedServices service = new TestManagedServices(getContext(), mLock, mUserProfiles, mIpm,
- APPROVAL_BY_COMPONENT);
-
- SparseArray<ArraySet<ComponentName>> approvedComponentsByUser = new SparseArray<>();
- ArraySet<ComponentName> allowed = new ArraySet<>();
- allowed.add(ComponentName.unflattenFromString("pkg1/cmp1"));
- approvedComponentsByUser.put(11, allowed);
- IntArray users = new IntArray();
- users.add(11);
-
- SparseArray<Set<ComponentName>> componentsToBind = new SparseArray<>();
-
- service.populateComponentsToBind(componentsToBind, users, approvedComponentsByUser,
- /* isVisibleBackgroundUser= */ true);
-
- assertEquals(1, componentsToBind.size());
- assertEquals(1, componentsToBind.get(11).size());
- assertTrue(componentsToBind.get(11).contains(ComponentName.unflattenFromString(
- "pkg1/cmp1")));
- assertThat(service.isComponentEnabledForCurrentProfiles(
- new ComponentName("pkg1", "cmp1"))).isFalse();
- assertThat(service.isComponentEnabledForPackage("pkg1")).isFalse();
- }
-
@Test
public void testOnNullBinding() throws Exception {
Context context = mock(Context.class);
diff --git a/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutTests.java b/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutTests.java
index 28ae271e20fc..cf5323e1f3a5 100644
--- a/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutTests.java
+++ b/services/tests/wmtests/src/com/android/server/policy/ModifierShortcutTests.java
@@ -288,7 +288,6 @@ public class ModifierShortcutTests extends ShortcutKeyTestBase {
* Sends a KEYCODE_SCREENSHOT and validates screenshot is taken if flag is enabled
*/
@Test
- @EnableFlags(com.android.hardware.input.Flags.FLAG_EMOJI_AND_SCREENSHOT_KEYCODES_AVAILABLE)
@DisableFlags(com.android.hardware.input.Flags.FLAG_USE_KEY_GESTURE_EVENT_HANDLER)
public void testTakeScreenshot_flagEnabled() {
sendKeyCombination(new int[]{KEYCODE_SCREENSHOT}, 0);
@@ -296,17 +295,6 @@ public class ModifierShortcutTests extends ShortcutKeyTestBase {
}
/**
- * Sends a KEYCODE_SCREENSHOT and validates screenshot is not taken if flag is disabled
- */
- @Test
- @DisableFlags({com.android.hardware.input.Flags.FLAG_EMOJI_AND_SCREENSHOT_KEYCODES_AVAILABLE,
- com.android.hardware.input.Flags.FLAG_USE_KEY_GESTURE_EVENT_HANDLER})
- public void testTakeScreenshot_flagDisabled() {
- sendKeyCombination(new int[]{KEYCODE_SCREENSHOT}, 0);
- mPhoneWindowManager.assertTakeScreenshotNotCalled();
- }
-
- /**
* META+CTRL+BACKSPACE for taking a bugreport when the flag is enabled.
*/
@Test
diff --git a/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java b/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java
index 6596ee935b4b..a51ce9951ab4 100644
--- a/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java
+++ b/services/tests/wmtests/src/com/android/server/policy/TestPhoneWindowManager.java
@@ -699,8 +699,8 @@ class TestPhoneWindowManager {
void assertPowerWakeUp() {
mTestLooper.dispatchAll();
- verify(mWindowWakeUpPolicy)
- .wakeUpFromKey(anyLong(), eq(KeyEvent.KEYCODE_POWER), anyBoolean());
+ verify(mWindowWakeUpPolicy).wakeUpFromKey(
+ eq(DEFAULT_DISPLAY), anyLong(), eq(KeyEvent.KEYCODE_POWER), anyBoolean());
}
void assertNoPowerSleep() {
diff --git a/services/tests/wmtests/src/com/android/server/policy/WindowWakeUpPolicyTests.java b/services/tests/wmtests/src/com/android/server/policy/WindowWakeUpPolicyTests.java
index 7322e5a3b681..3ca352cfa60d 100644
--- a/services/tests/wmtests/src/com/android/server/policy/WindowWakeUpPolicyTests.java
+++ b/services/tests/wmtests/src/com/android/server/policy/WindowWakeUpPolicyTests.java
@@ -22,6 +22,7 @@ import static android.os.PowerManager.WAKE_REASON_GESTURE;
import static android.os.PowerManager.WAKE_REASON_POWER_BUTTON;
import static android.os.PowerManager.WAKE_REASON_WAKE_KEY;
import static android.os.PowerManager.WAKE_REASON_WAKE_MOTION;
+import static android.view.Display.DEFAULT_DISPLAY;
import static android.view.InputDevice.SOURCE_ROTARY_ENCODER;
import static android.view.InputDevice.SOURCE_TOUCHSCREEN;
import static android.view.KeyEvent.KEYCODE_HOME;
@@ -35,6 +36,7 @@ import static com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraL
import static com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch;
import static com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture;
import static com.android.server.policy.Flags.FLAG_SUPPORT_INPUT_WAKEUP_DELEGATE;
+import static com.android.server.power.feature.flags.Flags.FLAG_PER_DISPLAY_WAKE_BY_TOUCH;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
@@ -43,6 +45,7 @@ import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@@ -52,6 +55,8 @@ import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.os.PowerManager;
+import android.platform.test.annotations.DisableFlags;
+import android.platform.test.annotations.EnableFlags;
import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.Settings;
import android.view.Display;
@@ -125,6 +130,7 @@ public final class WindowWakeUpPolicyTests {
}
@Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testMotionWakeUpDelegation_wakePowerManagerIfDelegateDoesNotHandleWake() {
setTheaterModeEnabled(false);
mSetFlagsRule.enableFlags(FLAG_SUPPORT_INPUT_WAKEUP_DELEGATE);
@@ -136,7 +142,8 @@ public final class WindowWakeUpPolicyTests {
// Verify the policy wake up call succeeds because of the call on the delegate, and not
// because of a PowerManager wake up.
- assertThat(mPolicy.wakeUpFromMotion(200, SOURCE_TOUCHSCREEN, true)).isTrue();
+ assertThat(mPolicy.wakeUpFromMotion(
+ mDefaultDisplay.getDisplayId(), 200, SOURCE_TOUCHSCREEN, true)).isTrue();
verify(mInputWakeUpDelegate).wakeUpFromMotion(200, SOURCE_TOUCHSCREEN, true);
verifyNoPowerManagerWakeUp();
@@ -144,12 +151,14 @@ public final class WindowWakeUpPolicyTests {
// Verify the policy wake up call succeeds because of the PowerManager wake up, since the
// delegate would not handle the wake up request.
- assertThat(mPolicy.wakeUpFromMotion(300, SOURCE_ROTARY_ENCODER, false)).isTrue();
+ assertThat(mPolicy.wakeUpFromMotion(
+ mDefaultDisplay.getDisplayId(), 300, SOURCE_ROTARY_ENCODER, false)).isTrue();
verify(mInputWakeUpDelegate).wakeUpFromMotion(300, SOURCE_ROTARY_ENCODER, false);
verify(mPowerManager).wakeUp(300, WAKE_REASON_WAKE_MOTION, "android.policy:MOTION");
}
@Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testKeyWakeUpDelegation_wakePowerManagerIfDelegateDoesNotHandleWake() {
setTheaterModeEnabled(false);
mSetFlagsRule.enableFlags(FLAG_SUPPORT_INPUT_WAKEUP_DELEGATE);
@@ -161,7 +170,7 @@ public final class WindowWakeUpPolicyTests {
// Verify the policy wake up call succeeds because of the call on the delegate, and not
// because of a PowerManager wake up.
- assertThat(mPolicy.wakeUpFromKey(200, KEYCODE_POWER, true)).isTrue();
+ assertThat(mPolicy.wakeUpFromKey(DEFAULT_DISPLAY, 200, KEYCODE_POWER, true)).isTrue();
verify(mInputWakeUpDelegate).wakeUpFromKey(200, KEYCODE_POWER, true);
verifyNoPowerManagerWakeUp();
@@ -169,7 +178,8 @@ public final class WindowWakeUpPolicyTests {
// Verify the policy wake up call succeeds because of the PowerManager wake up, since the
// delegate would not handle the wake up request.
- assertThat(mPolicy.wakeUpFromKey(300, KEYCODE_STEM_PRIMARY, false)).isTrue();
+ assertThat(mPolicy.wakeUpFromKey(
+ DEFAULT_DISPLAY, 300, KEYCODE_STEM_PRIMARY, false)).isTrue();
verify(mInputWakeUpDelegate).wakeUpFromKey(300, KEYCODE_STEM_PRIMARY, false);
verify(mPowerManager).wakeUp(300, WAKE_REASON_WAKE_KEY, "android.policy:KEY");
}
@@ -186,7 +196,7 @@ public final class WindowWakeUpPolicyTests {
.setInputWakeUpDelegate(mInputWakeUpDelegate);
// Check that the wake up does not happen because the theater mode policy check fails.
- assertThat(mPolicy.wakeUpFromKey(200, KEYCODE_POWER, true)).isFalse();
+ assertThat(mPolicy.wakeUpFromKey(DEFAULT_DISPLAY, 200, KEYCODE_POWER, true)).isFalse();
verify(mInputWakeUpDelegate, never()).wakeUpFromKey(anyLong(), anyInt(), anyBoolean());
}
@@ -201,11 +211,13 @@ public final class WindowWakeUpPolicyTests {
.setInputWakeUpDelegate(mInputWakeUpDelegate);
// Check that the wake up does not happen because the theater mode policy check fails.
- assertThat(mPolicy.wakeUpFromMotion(200, SOURCE_TOUCHSCREEN, true)).isFalse();
+ assertThat(mPolicy.wakeUpFromMotion(
+ mDefaultDisplay.getDisplayId(), 200, SOURCE_TOUCHSCREEN, true)).isFalse();
verify(mInputWakeUpDelegate, never()).wakeUpFromMotion(anyLong(), anyInt(), anyBoolean());
}
@Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testTheaterModeChecksNotAppliedWhenScreenIsOn() {
mSetFlagsRule.enableFlags(FLAG_SUPPORT_INPUT_WAKEUP_DELEGATE);
setDefaultDisplayState(Display.STATE_ON);
@@ -213,30 +225,69 @@ public final class WindowWakeUpPolicyTests {
setBooleanRes(config_allowTheaterModeWakeFromMotion, false);
mPolicy = new WindowWakeUpPolicy(mContextSpy, mClock);
- mPolicy.wakeUpFromMotion(200L, SOURCE_TOUCHSCREEN, true);
+ mPolicy.wakeUpFromMotion(mDefaultDisplay.getDisplayId(), 200L, SOURCE_TOUCHSCREEN, true);
verify(mPowerManager).wakeUp(200L, WAKE_REASON_WAKE_MOTION, "android.policy:MOTION");
}
@Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testWakeUpFromMotion() {
runPowerManagerUpChecks(
- () -> mPolicy.wakeUpFromMotion(mClock.uptimeMillis(), SOURCE_TOUCHSCREEN, true),
+ () -> mPolicy.wakeUpFromMotion(mDefaultDisplay.getDisplayId(),
+ mClock.uptimeMillis(), SOURCE_TOUCHSCREEN, true),
config_allowTheaterModeWakeFromMotion,
WAKE_REASON_WAKE_MOTION,
"android.policy:MOTION");
}
@Test
+ @EnableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
+ public void testWakeUpFromMotion_perDisplayWakeByTouchEnabled() {
+ setTheaterModeEnabled(false);
+ final int displayId = 555;
+ mPolicy = new WindowWakeUpPolicy(mContextSpy, mClock);
+
+ boolean displayWokeUp = mPolicy.wakeUpFromMotion(
+ displayId, mClock.uptimeMillis(), SOURCE_TOUCHSCREEN, /* isDown= */ true);
+
+ // Verify that display is woken up
+ assertThat(displayWokeUp).isTrue();
+ verify(mPowerManager).wakeUp(anyLong(), eq(WAKE_REASON_WAKE_MOTION),
+ eq("android.policy:MOTION"), eq(displayId));
+ }
+
+ @Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
+ public void testWakeUpFromMotion_perDisplayWakeByTouchDisabled() {
+ setTheaterModeEnabled(false);
+ final int displayId = 555;
+ mPolicy = new WindowWakeUpPolicy(mContextSpy, mClock);
+
+ boolean displayWokeUp = mPolicy.wakeUpFromMotion(
+ displayId, mClock.uptimeMillis(), SOURCE_TOUCHSCREEN, /* isDown= */ true);
+
+ // Verify that power is woken up and display isn't woken up individually
+ assertThat(displayWokeUp).isTrue();
+ verify(mPowerManager).wakeUp(
+ anyLong(), eq(WAKE_REASON_WAKE_MOTION), eq("android.policy:MOTION"));
+ verify(mPowerManager, never()).wakeUp(anyLong(), eq(WAKE_REASON_WAKE_MOTION),
+ eq("android.policy:MOTION"), eq(displayId));
+ }
+
+ @Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testWakeUpFromKey_nonPowerKey() {
runPowerManagerUpChecks(
- () -> mPolicy.wakeUpFromKey(mClock.uptimeMillis(), KEYCODE_HOME, true),
+ () -> mPolicy.wakeUpFromKey(
+ DEFAULT_DISPLAY, mClock.uptimeMillis(), KEYCODE_HOME, true),
config_allowTheaterModeWakeFromKey,
WAKE_REASON_WAKE_KEY,
"android.policy:KEY");
}
@Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testWakeUpFromKey_powerKey() {
// Disable the resource affecting all wake keys because it affects power key as well.
// That way, power key wake during theater mode will solely be controlled by
@@ -245,7 +296,8 @@ public final class WindowWakeUpPolicyTests {
// Test with power key
runPowerManagerUpChecks(
- () -> mPolicy.wakeUpFromKey(mClock.uptimeMillis(), KEYCODE_POWER, true),
+ () -> mPolicy.wakeUpFromKey(
+ DEFAULT_DISPLAY, mClock.uptimeMillis(), KEYCODE_POWER, true),
config_allowTheaterModeWakeFromPowerKey,
WAKE_REASON_POWER_BUTTON,
"android.policy:POWER");
@@ -254,13 +306,31 @@ public final class WindowWakeUpPolicyTests {
// even if the power-key specific theater mode config is disabled.
setBooleanRes(config_allowTheaterModeWakeFromPowerKey, false);
runPowerManagerUpChecks(
- () -> mPolicy.wakeUpFromKey(mClock.uptimeMillis(), KEYCODE_POWER, false),
+ () -> mPolicy.wakeUpFromKey(
+ DEFAULT_DISPLAY, mClock.uptimeMillis(), KEYCODE_POWER, false),
config_allowTheaterModeWakeFromKey,
WAKE_REASON_POWER_BUTTON,
"android.policy:POWER");
}
@Test
+ @EnableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
+ public void testWakeUpFromKey_invalidDisplay_perDisplayWakeByTouchEnabled() {
+ setTheaterModeEnabled(false);
+ final int displayId = Display.INVALID_DISPLAY;
+ mPolicy = new WindowWakeUpPolicy(mContextSpy, mClock);
+
+ boolean displayWokeUp = mPolicy.wakeUpFromKey(
+ displayId, mClock.uptimeMillis(), KEYCODE_POWER, /* isDown= */ false);
+
+ // Verify that default display is woken up
+ assertThat(displayWokeUp).isTrue();
+ verify(mPowerManager).wakeUp(anyLong(), eq(WAKE_REASON_POWER_BUTTON),
+ eq("android.policy:POWER"), eq(DEFAULT_DISPLAY));
+ }
+
+ @Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testWakeUpFromLid() {
runPowerManagerUpChecks(
() -> mPolicy.wakeUpFromLid(),
@@ -270,6 +340,7 @@ public final class WindowWakeUpPolicyTests {
}
@Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testWakeUpFromWakeGesture() {
runPowerManagerUpChecks(
() -> mPolicy.wakeUpFromWakeGesture(),
@@ -279,6 +350,7 @@ public final class WindowWakeUpPolicyTests {
}
@Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testwakeUpFromCameraCover() {
runPowerManagerUpChecks(
() -> mPolicy.wakeUpFromCameraCover(mClock.uptimeMillis()),
@@ -288,6 +360,7 @@ public final class WindowWakeUpPolicyTests {
}
@Test
+ @DisableFlags({FLAG_PER_DISPLAY_WAKE_BY_TOUCH})
public void testWakeUpFromPowerKeyCameraGesture() {
// Disable the resource affecting all wake keys because it affects power key as well.
// That way, power key wake during theater mode will solely be controlled by
diff --git a/telephony/java/android/telephony/satellite/EarfcnRange.aidl b/telephony/java/android/telephony/satellite/EarfcnRange.aidl
new file mode 100644
index 000000000000..0b224d0b09bd
--- /dev/null
+++ b/telephony/java/android/telephony/satellite/EarfcnRange.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2024, 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.telephony.satellite;
+
+parcelable EarfcnRange;
diff --git a/telephony/java/android/telephony/satellite/EarfcnRange.java b/telephony/java/android/telephony/satellite/EarfcnRange.java
new file mode 100644
index 000000000000..38043b570c2f
--- /dev/null
+++ b/telephony/java/android/telephony/satellite/EarfcnRange.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2024 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.telephony.satellite;
+
+import android.annotation.FlaggedApi;
+import android.annotation.IntRange;
+import android.annotation.NonNull;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import com.android.internal.telephony.flags.Flags;
+
+/**
+ * EARFCN (E-UTRA Absolute Radio Frequency Channel Number): A number that identifies a
+ * specific frequency channel in LTE/5G NR, used to define the carrier frequency.
+ * The range can be [0 ~ 65535] according to the 3GPP TS 36.101
+ *
+ * In satellite communication:
+ * - Efficient frequency allocation across a wide coverage area.
+ * - Handles Doppler shift due to satellite movement.
+ * - Manages interference with terrestrial networks.
+ *
+ * See 3GPP TS 36.101 and 38.101-1 for details.
+ *
+ * @hide
+ */
+@FlaggedApi(Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
+public final class EarfcnRange implements Parcelable {
+
+ /**
+ * The start frequency of the earfcn range and is inclusive in the range
+ */
+ private int mStartEarfcn;
+
+ /**
+ * The end frequency of the earfcn range and is inclusive in the range.
+ */
+ private int mEndEarfcn;
+
+ private EarfcnRange(@NonNull Parcel in) {
+ readFromParcel(in);
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(mStartEarfcn);
+ dest.writeInt(mEndEarfcn);
+ }
+
+ private void readFromParcel(Parcel in) {
+ mStartEarfcn = in.readInt();
+ mEndEarfcn = in.readInt();
+ }
+
+ /**
+ * Constructor for the EarfcnRange class.
+ * The range can be [0 ~ 65535] according to the 3GPP TS 36.101
+ *
+ * @param startEarfcn The starting earfcn value.
+ * @param endEarfcn The ending earfcn value.
+ */
+ public EarfcnRange(@IntRange(from = 0, to = 65535) int endEarfcn,
+ @IntRange(from = 0, to = 65535) int startEarfcn) {
+ mEndEarfcn = endEarfcn;
+ mStartEarfcn = startEarfcn;
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public String toString() {
+ return "startEarfcn: " + mStartEarfcn + ", " + "endEarfcn: " + mEndEarfcn;
+ }
+
+ @NonNull
+ public static final Creator<EarfcnRange> CREATOR = new Creator<EarfcnRange>() {
+ @Override
+ public EarfcnRange createFromParcel(Parcel in) {
+ return new EarfcnRange(in);
+ }
+
+ @Override
+ public EarfcnRange[] newArray(int size) {
+ return new EarfcnRange[size];
+ }
+ };
+
+ /**
+ * Returns the starting earfcn value for this range.
+ * It can be [0 ~ 65535] according to the 3GPP TS 36.101
+ *
+ * @return The starting earfcn.
+ */
+ public @IntRange(from = 0, to = 65535) int getStartEarfcn() {
+ return mStartEarfcn;
+ }
+
+ /**
+ * Returns the ending earfcn value for this range.
+ * It can be [0 ~ 65535] according to the 3GPP TS 36.101
+ *
+ * @return The ending earfcn.
+ */
+ public @IntRange(from = 0, to = 65535) int getEndEarfcn() {
+ return mEndEarfcn;
+ }
+}
diff --git a/telephony/java/android/telephony/satellite/ISatelliteCommunicationAllowedStateCallback.aidl b/telephony/java/android/telephony/satellite/ISatelliteCommunicationAllowedStateCallback.aidl
index a7eda482cb76..2730f90c4e5e 100644
--- a/telephony/java/android/telephony/satellite/ISatelliteCommunicationAllowedStateCallback.aidl
+++ b/telephony/java/android/telephony/satellite/ISatelliteCommunicationAllowedStateCallback.aidl
@@ -16,6 +16,8 @@
package android.telephony.satellite;
+import android.telephony.satellite.SatelliteAccessConfiguration;
+
/**
* Interface for satellite communication allowed state callback.
* @hide
@@ -29,4 +31,14 @@ oneway interface ISatelliteCommunicationAllowedStateCallback {
* @param allowed whether satellite communication state or not
*/
void onSatelliteCommunicationAllowedStateChanged(in boolean isAllowed);
+
+ /**
+ * Callback method invoked when the satellite access configuration changes
+ *
+ * @param The satellite access configuration associated with the current location.
+ * When satellite is not allowed at the current location,
+ * {@code satelliteRegionalConfiguration} will be null.
+ */
+ void onSatelliteAccessConfigurationChanged(in SatelliteAccessConfiguration
+ satelliteAccessConfiguration);
}
diff --git a/telephony/java/android/telephony/satellite/SatelliteAccessConfiguration.aidl b/telephony/java/android/telephony/satellite/SatelliteAccessConfiguration.aidl
new file mode 100644
index 000000000000..0214193a654f
--- /dev/null
+++ b/telephony/java/android/telephony/satellite/SatelliteAccessConfiguration.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2024, 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.telephony.satellite;
+
+ parcelable SatelliteAccessConfiguration; \ No newline at end of file
diff --git a/telephony/java/android/telephony/satellite/SatelliteAccessConfiguration.java b/telephony/java/android/telephony/satellite/SatelliteAccessConfiguration.java
new file mode 100644
index 000000000000..c3ae70b48854
--- /dev/null
+++ b/telephony/java/android/telephony/satellite/SatelliteAccessConfiguration.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2024 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.telephony.satellite;
+
+import android.annotation.FlaggedApi;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import androidx.annotation.NonNull;
+
+import com.android.internal.telephony.flags.Flags;
+
+import java.util.List;
+
+/**
+ * SatelliteAccessConfiguration is used to store satellite access configuration
+ * that will be applied to the satellite communication at the corresponding region.
+ *
+ * @hide
+ */
+@FlaggedApi(Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
+public final class SatelliteAccessConfiguration implements Parcelable {
+ /**
+ * The list of satellites available at the current location.
+ */
+ @NonNull
+ private List<SatelliteInfo> mSatelliteInfoList;
+
+ /**
+ * The list of tag IDs associated with the current location
+ */
+ @NonNull
+ private int[] mTagIds;
+
+ /**
+ * Constructor for {@link SatelliteAccessConfiguration}.
+ *
+ * @param satelliteInfos The list of {@link SatelliteInfo} objects representing the satellites
+ * accessible with this configuration.
+ * @param tagIds The list of tag IDs associated with this configuration.
+ */
+ public SatelliteAccessConfiguration(@NonNull List<SatelliteInfo> satelliteInfos,
+ @NonNull int[] tagIds) {
+ mSatelliteInfoList = satelliteInfos;
+ mTagIds = tagIds;
+ }
+
+ public SatelliteAccessConfiguration(Parcel in) {
+ mSatelliteInfoList = in.createTypedArrayList(SatelliteInfo.CREATOR);
+ mTagIds = new int[in.readInt()];
+ in.readIntArray(mTagIds);
+ }
+
+ public static final Creator<SatelliteAccessConfiguration> CREATOR =
+ new Creator<SatelliteAccessConfiguration>() {
+ @Override
+ public SatelliteAccessConfiguration createFromParcel(Parcel in) {
+ return new SatelliteAccessConfiguration(in);
+ }
+
+ @Override
+ public SatelliteAccessConfiguration[] newArray(int size) {
+ return new SatelliteAccessConfiguration[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * @param dest The Parcel in which the object should be written.
+ * @param flags Additional flags about how the object should be written.
+ * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
+ */
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeTypedList(mSatelliteInfoList);
+ if (mTagIds != null && mTagIds.length > 0) {
+ dest.writeInt(mTagIds.length);
+ dest.writeIntArray(mTagIds);
+ } else {
+ dest.writeInt(0);
+ }
+ }
+
+ /**
+ * Returns a list of {@link SatelliteInfo} objects representing the satellites
+ * associated with this object.
+ *
+ * @return The list of {@link SatelliteInfo} objects.
+ */
+ @NonNull
+ public List<SatelliteInfo> getSatelliteInfos() {
+ return mSatelliteInfoList;
+ }
+
+ /**
+ * Returns a list of tag IDs associated with this object.
+ *
+ * @return The list of tag IDs.
+ */
+ @NonNull
+ public int[] getTagIds() {
+ return mTagIds;
+ }
+}
diff --git a/telephony/java/android/telephony/satellite/SatelliteCommunicationAllowedStateCallback.java b/telephony/java/android/telephony/satellite/SatelliteCommunicationAllowedStateCallback.java
index 1a870202d096..bffb11f23d56 100644
--- a/telephony/java/android/telephony/satellite/SatelliteCommunicationAllowedStateCallback.java
+++ b/telephony/java/android/telephony/satellite/SatelliteCommunicationAllowedStateCallback.java
@@ -17,6 +17,7 @@
package android.telephony.satellite;
import android.annotation.FlaggedApi;
+import android.annotation.Nullable;
import com.android.internal.telephony.flags.Flags;
@@ -40,4 +41,17 @@ public interface SatelliteCommunicationAllowedStateCallback {
*/
@FlaggedApi(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
void onSatelliteCommunicationAllowedStateChanged(boolean isAllowed);
+
+ /**
+ * Callback method invoked when the satellite access configuration changes
+ *
+ * @param satelliteAccessConfiguration The satellite access configuration associated with
+ * the current location. When satellite is not allowed at
+ * the current location,
+ * {@code satelliteRegionalConfiguration} will be null.
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
+ default void onSatelliteAccessConfigurationChanged(
+ @Nullable SatelliteAccessConfiguration satelliteAccessConfiguration) {};
}
diff --git a/telephony/java/android/telephony/satellite/SatelliteInfo.aidl b/telephony/java/android/telephony/satellite/SatelliteInfo.aidl
new file mode 100644
index 000000000000..fc2303b080a5
--- /dev/null
+++ b/telephony/java/android/telephony/satellite/SatelliteInfo.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2024, 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.telephony.satellite;
+
+ parcelable SatelliteInfo; \ No newline at end of file
diff --git a/telephony/java/android/telephony/satellite/SatelliteInfo.java b/telephony/java/android/telephony/satellite/SatelliteInfo.java
new file mode 100644
index 000000000000..bca907e49993
--- /dev/null
+++ b/telephony/java/android/telephony/satellite/SatelliteInfo.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2024 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.telephony.satellite;
+
+import android.annotation.FlaggedApi;
+import android.os.Parcel;
+import android.os.ParcelUuid;
+import android.os.Parcelable;
+
+import androidx.annotation.NonNull;
+
+import com.android.internal.telephony.flags.Flags;
+
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * SatelliteInfo stores a satellite's identification, position, and frequency information
+ * facilitating efficient satellite communications.
+ *
+ * @hide
+ */
+@FlaggedApi(Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
+public class SatelliteInfo implements Parcelable {
+ /**
+ * Unique identification number for the satellite.
+ * This ID is used to distinguish between different satellites in the network.
+ */
+ @NonNull
+ private UUID mId;
+
+ /**
+ * Position information of a satellite.
+ * This includes the longitude and altitude of the satellite.
+ */
+ private SatellitePosition mPosition;
+
+ /**
+ * The frequency bands to scan. Bands and earfcns won't overlap.
+ * Bands will be filled only if the whole band is needed.
+ * Maximum length of the vector is 8.
+ */
+ private int[] mBands;
+
+ /**
+ * EARFCN (E-UTRA Absolute Radio Frequency Channel Number) Ranges
+ * The supported frequency range list.
+ * Maximum length of the vector is 8.
+ */
+ private final List<EarfcnRange> mEarfcnRangeList;
+
+ protected SatelliteInfo(Parcel in) {
+ ParcelUuid parcelUuid = in.readParcelable(
+ ParcelUuid.class.getClassLoader(), ParcelUuid.class);
+ if (parcelUuid != null) {
+ mId = parcelUuid.getUuid();
+ }
+ mPosition = in.readParcelable(SatellitePosition.class.getClassLoader(),
+ SatellitePosition.class);
+ int numBands = in.readInt();
+ mBands = new int[numBands];
+ if (numBands > 0) {
+ for (int i = 0; i < numBands; i++) {
+ mBands[i] = in.readInt();
+ }
+ }
+ mEarfcnRangeList = in.createTypedArrayList(EarfcnRange.CREATOR);
+ }
+
+ /**
+ * Constructor for {@link SatelliteInfo}.
+ *
+ * @param satelliteId The ID of the satellite.
+ * @param satellitePosition The {@link SatellitePosition} of the satellite.
+ * @param bands The list of frequency bands supported by the satellite.
+ * @param earfcnRanges The list of {@link EarfcnRange} objects representing the EARFCN
+ * ranges supported by the satellite.
+ */
+ public SatelliteInfo(@NonNull UUID satelliteId, @NonNull SatellitePosition satellitePosition,
+ @NonNull int[] bands, @NonNull List<EarfcnRange> earfcnRanges) {
+ mId = satelliteId;
+ mPosition = satellitePosition;
+ mBands = bands;
+ mEarfcnRangeList = earfcnRanges;
+ }
+
+ public static final Creator<SatelliteInfo> CREATOR = new Creator<SatelliteInfo>() {
+ @Override
+ public SatelliteInfo createFromParcel(Parcel in) {
+ return new SatelliteInfo(in);
+ }
+
+ @Override
+ public SatelliteInfo[] newArray(int size) {
+ return new SatelliteInfo[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeParcelable(new ParcelUuid(mId), flags);
+ dest.writeParcelable(mPosition, flags);
+ if (mBands != null && mBands.length > 0) {
+ dest.writeInt(mBands.length);
+ dest.writeIntArray(mBands);
+ } else {
+ dest.writeInt(0);
+ }
+ dest.writeTypedList(mEarfcnRangeList);
+ }
+
+ /**
+ * Returns the ID of the satellite.
+ *
+ * @return The satellite ID.
+ */
+ @NonNull
+ public UUID getSatelliteId() {
+ return mId;
+ }
+
+ /**
+ * Returns the position of the satellite.
+ *
+ * @return The {@link SatellitePosition} of the satellite.
+ */
+ public SatellitePosition getSatellitePosition() {
+ return mPosition;
+ }
+
+ /**
+ * Returns the list of frequency bands supported by the satellite.
+ *
+ * @return The list of frequency bands.
+ */
+ @NonNull
+ public int[] getBands() {
+ return mBands;
+ }
+
+ /**
+ * Returns the list of EARFCN ranges supported by the satellite.
+ *
+ * @return The list of {@link EarfcnRange} objects.
+ */
+ @NonNull
+ public List<EarfcnRange> getEarfcnRanges() {
+ return mEarfcnRangeList;
+ }
+}
diff --git a/telephony/java/android/telephony/satellite/SatelliteManager.java b/telephony/java/android/telephony/satellite/SatelliteManager.java
index 88dddcfc9180..7e3d99a5c4ac 100644
--- a/telephony/java/android/telephony/satellite/SatelliteManager.java
+++ b/telephony/java/android/telephony/satellite/SatelliteManager.java
@@ -36,6 +36,7 @@ import android.os.ICancellationSignal;
import android.os.OutcomeReceiver;
import android.os.RemoteException;
import android.os.ResultReceiver;
+import android.telephony.CarrierConfigManager;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyCallback;
import android.telephony.TelephonyFrameworkInitializer;
@@ -272,6 +273,14 @@ public final class SatelliteManager {
public static final String KEY_DEPROVISION_SATELLITE_TOKENS = "deprovision_satellite";
/**
+ * Bundle key to get the response from
+ * {@link #requestSatelliteAccessConfigurationForCurrentLocation(Executor, OutcomeReceiver)}.
+ * @hide
+ */
+ public static final String KEY_SATELLITE_ACCESS_CONFIGURATION =
+ "satellite_access_configuration";
+
+ /**
* The request was successfully processed.
* @hide
*/
@@ -2332,6 +2341,68 @@ public final class SatelliteManager {
}
/**
+ * Request to get satellite access configuration for the current location.
+ *
+ * @param executor The executor on which the callback will be called.
+ * @param callback The callback object to which the result will be delivered.
+ * If the request is successful, {@link OutcomeReceiver#onResult(Object)}
+ * will return a {@code SatelliteAccessConfiguration} with value the regional
+ * satellite access configuration at the current location.
+ * If the request is not successful, {@link OutcomeReceiver#onError(Throwable)}
+ * will return a {@link SatelliteException} with the {@link SatelliteResult}.
+ *
+ * @throws SecurityException if the caller doesn't have required permission.
+ *
+ * @hide
+ */
+ @RequiresPermission(Manifest.permission.SATELLITE_COMMUNICATION)
+ @FlaggedApi(Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
+ public void requestSatelliteAccessConfigurationForCurrentLocation(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull OutcomeReceiver<SatelliteAccessConfiguration, SatelliteException> callback) {
+ Objects.requireNonNull(executor);
+ Objects.requireNonNull(callback);
+
+ try {
+ ITelephony telephony = getITelephony();
+ if (telephony != null) {
+ ResultReceiver receiver = new ResultReceiver(null) {
+ @Override
+ protected void onReceiveResult(int resultCode, Bundle resultData) {
+ if (resultCode == SATELLITE_RESULT_SUCCESS) {
+ if (resultData.containsKey(KEY_SATELLITE_ACCESS_CONFIGURATION)) {
+ SatelliteAccessConfiguration satelliteAccessConfiguration =
+ resultData.getParcelable(KEY_SATELLITE_ACCESS_CONFIGURATION,
+ SatelliteAccessConfiguration.class);
+ executor.execute(() -> Binder.withCleanCallingIdentity(() ->
+ callback.onResult(satelliteAccessConfiguration)));
+ } else {
+ loge("KEY_SATELLITE_ACCESS_CONFIGURATION does not exist.");
+ executor.execute(() -> Binder.withCleanCallingIdentity(() ->
+ callback.onError(new SatelliteException(
+ SATELLITE_RESULT_REQUEST_FAILED))));
+ }
+ } else {
+ executor.execute(() -> Binder.withCleanCallingIdentity(() ->
+ callback.onError(new SatelliteException(resultCode))));
+ }
+ }
+ };
+ telephony.requestSatelliteAccessConfigurationForCurrentLocation(receiver);
+ } else {
+ loge("requestSatelliteAccessConfigurationForCurrentLocation() invalid telephony");
+ executor.execute(() -> Binder.withCleanCallingIdentity(() -> callback.onError(
+ new SatelliteException(SATELLITE_RESULT_ILLEGAL_STATE))));
+ }
+ } catch (RemoteException ex) {
+ loge("requestSatelliteAccessConfigurationForCurrentLocation() RemoteException: "
+ + ex);
+ executor.execute(() -> Binder.withCleanCallingIdentity(() -> callback.onError(
+ new SatelliteException(SATELLITE_RESULT_ILLEGAL_STATE))));
+ }
+ }
+
+ /**
* Request to get the duration in seconds after which the satellite will be visible.
* This will be {@link Duration#ZERO} if the satellite is currently visible.
*
@@ -2436,7 +2507,7 @@ public final class SatelliteManager {
* <li>There is no satellite communication restriction, which is added by
* {@link #addAttachRestrictionForCarrier(int, int, Executor, Consumer)}</li>
* <li>The carrier config {@link
- * android.telephony.CarrierConfigManager#KEY_SATELLITE_ATTACH_SUPPORTED_BOOL} is set to
+ * CarrierConfigManager#KEY_SATELLITE_ATTACH_SUPPORTED_BOOL} is set to
* {@code true}.</li>
* </ul>
*
@@ -2759,7 +2830,7 @@ public final class SatelliteManager {
* <p>
* Note: This API is specifically designed for OEM enabled satellite connectivity only.
* For satellite connectivity enabled using carrier roaming, please refer to
- * {@link android.telephony.TelephonyCallback.SignalStrengthsListener}, and
+ * {@link TelephonyCallback.SignalStrengthsListener}, and
* {@link TelephonyManager#registerTelephonyCallback(Executor, TelephonyCallback)}.
* </p>
*
@@ -2830,7 +2901,7 @@ public final class SatelliteManager {
* <p>
* Note: This API is specifically designed for OEM enabled satellite connectivity only.
* For satellite connectivity enabled using carrier roaming, please refer to
- * {@link android.telephony.TelephonyCallback.SignalStrengthsListener}, and
+ * {@link TelephonyCallback.SignalStrengthsListener}, and
* {@link TelephonyManager#registerTelephonyCallback(Executor, TelephonyCallback)}.
* </p>
*
@@ -3147,6 +3218,15 @@ public final class SatelliteManager {
() -> callback.onSatelliteCommunicationAllowedStateChanged(
isAllowed)));
}
+
+ @Override
+ public void onSatelliteAccessConfigurationChanged(
+ @Nullable SatelliteAccessConfiguration
+ satelliteAccessConfiguration) {
+ executor.execute(() -> Binder.withCleanCallingIdentity(
+ () -> callback.onSatelliteAccessConfigurationChanged(
+ satelliteAccessConfiguration)));
+ }
};
sSatelliteCommunicationAllowedStateCallbackMap.put(callback, internalCallback);
return telephony.registerForCommunicationAllowedStateChanged(
diff --git a/telephony/java/android/telephony/satellite/SatellitePosition.aidl b/telephony/java/android/telephony/satellite/SatellitePosition.aidl
new file mode 100644
index 000000000000..a8028eb48ee7
--- /dev/null
+++ b/telephony/java/android/telephony/satellite/SatellitePosition.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2024, 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.telephony.satellite;
+
+ parcelable SatellitePosition; \ No newline at end of file
diff --git a/telephony/java/android/telephony/satellite/SatellitePosition.java b/telephony/java/android/telephony/satellite/SatellitePosition.java
new file mode 100644
index 000000000000..1e8c0180f456
--- /dev/null
+++ b/telephony/java/android/telephony/satellite/SatellitePosition.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2024 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.telephony.satellite;
+
+import android.annotation.FlaggedApi;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import androidx.annotation.NonNull;
+
+import com.android.internal.telephony.flags.Flags;
+
+/**
+ * The position of a satellite in Earth orbit.
+ *
+ * Longitude is the angular distance, measured in degrees, east or west of the prime longitude line
+ * ranging from -180 to 180 degrees
+ * Altitude is the distance from the center of the Earth to the satellite, measured in kilometers
+ *
+ * @hide
+ */
+@FlaggedApi(Flags.FLAG_CARRIER_ROAMING_NB_IOT_NTN)
+public class SatellitePosition implements Parcelable {
+
+ /**
+ * The longitude of the satellite in degrees, ranging from -180 to 180 degrees
+ */
+ private double mLongitudeDegree;
+
+ /**
+ * The distance from the center of the earth to the satellite, measured in kilometers
+ */
+ private double mAltitudeKm;
+
+ /**
+ * Constructor for {@link SatellitePosition} used to create an instance from a {@link Parcel}.
+ *
+ * @param in The {@link Parcel} to read the satellite position data from.
+ */
+ public SatellitePosition(Parcel in) {
+ mLongitudeDegree = in.readDouble();
+ mAltitudeKm = in.readDouble();
+ }
+
+ /**
+ * Constructor for {@link SatellitePosition}.
+ *
+ * @param longitudeDegree The longitude of the satellite in degrees.
+ * @param altitudeKm The altitude of the satellite in kilometers.
+ */
+ public SatellitePosition(double longitudeDegree, double altitudeKm) {
+ mLongitudeDegree = longitudeDegree;
+ mAltitudeKm = altitudeKm;
+ }
+
+ public static final Creator<SatellitePosition> CREATOR = new Creator<SatellitePosition>() {
+ @Override
+ public SatellitePosition createFromParcel(Parcel in) {
+ return new SatellitePosition(in);
+ }
+
+ @Override
+ public SatellitePosition[] newArray(int size) {
+ return new SatellitePosition[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * @param dest The Parcel in which the object should be written.
+ * @param flags Additional flags about how the object should be written.
+ * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
+ */
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeDouble(mLongitudeDegree);
+ dest.writeDouble(mAltitudeKm);
+ }
+
+ /**
+ * Returns the longitude of the satellite in degrees, ranging from -180 to 180 degrees.
+ *
+ * @return The longitude of the satellite.
+ */
+ public double getLongitudeDegrees() {
+ return mLongitudeDegree;
+ }
+
+ /**
+ * Returns the altitude of the satellite in kilometers
+ *
+ * @return The altitude of the satellite.
+ */
+ public double getAltitudeKm() {
+ return mAltitudeKm;
+ }
+}
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index 62cbb02c9fc7..210200be4cf3 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -886,7 +886,7 @@ interface ITelephony {
/**
* @return true if the ImsService to bind to for the slot id specified was set, false otherwise.
*/
- boolean setBoundImsServiceOverride(int slotIndex, boolean isCarrierService,
+ boolean setBoundImsServiceOverride(int slotIndex, int userId, boolean isCarrierService,
in int[] featureTypes, in String packageName);
/**
@@ -2999,6 +2999,16 @@ interface ITelephony {
void requestIsCommunicationAllowedForCurrentLocation(int subId, in ResultReceiver receiver);
/**
+ * Request to get satellite access configuration for the current location.
+ *
+ * @param receiver Result receiver to get the error code of the request
+ * and satellite access configuration for the current location.
+ */
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission("
+ + "android.Manifest.permission.SATELLITE_COMMUNICATION)")
+ void requestSatelliteAccessConfigurationForCurrentLocation(in ResultReceiver receiver);
+
+ /**
* Request to get the time after which the satellite will be visible.
*
* @param receiver Result receiver to get the error code of the request and the requested
diff --git a/tests/FlickerTests/test-apps/app-helpers/src/com/android/server/wm/flicker/helpers/DesktopModeAppHelper.kt b/tests/FlickerTests/test-apps/app-helpers/src/com/android/server/wm/flicker/helpers/DesktopModeAppHelper.kt
index 332b9b832037..9a9a331a3753 100644
--- a/tests/FlickerTests/test-apps/app-helpers/src/com/android/server/wm/flicker/helpers/DesktopModeAppHelper.kt
+++ b/tests/FlickerTests/test-apps/app-helpers/src/com/android/server/wm/flicker/helpers/DesktopModeAppHelper.kt
@@ -21,7 +21,7 @@ import android.graphics.Insets
import android.graphics.Rect
import android.graphics.Region
import android.os.SystemClock
-import android.platform.uiautomator_helpers.DeviceHelpers
+import android.platform.uiautomatorhelpers.DeviceHelpers
import android.tools.device.apphelpers.IStandardAppHelper
import android.tools.helpers.SYSTEMUI_PACKAGE
import android.tools.traces.parsers.WindowManagerStateHelper
@@ -159,7 +159,7 @@ open class DesktopModeAppHelper(private val innerHelper: IStandardAppHelper) :
) {
val caption = getCaptionForTheApp(wmHelper, device)
val maximizeButton = getMaximizeButtonForTheApp(caption)
- maximizeButton?.longClick()
+ maximizeButton.longClick()
wmHelper.StateSyncBuilder().withAppTransitionIdle().waitForAndVerify()
val buttonResId = if (toLeft) SNAP_LEFT_BUTTON else SNAP_RIGHT_BUTTON
diff --git a/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt b/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt
index 1574d1b7ce6f..61400edba165 100644
--- a/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt
+++ b/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt
@@ -757,7 +757,31 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_MINUS),
KeyEvent.META_ALT_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
- )
+ ),
+ TestData(
+ "META + ALT + '-' -> Magnifier Zoom Out",
+ intArrayOf(
+ KeyEvent.KEYCODE_META_LEFT,
+ KeyEvent.KEYCODE_ALT_LEFT,
+ KeyEvent.KEYCODE_MINUS
+ ),
+ KeyGestureEvent.KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_OUT,
+ intArrayOf(KeyEvent.KEYCODE_MINUS),
+ KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ ),
+ TestData(
+ "META + ALT + '=' -> Magnifier Zoom In",
+ intArrayOf(
+ KeyEvent.KEYCODE_META_LEFT,
+ KeyEvent.KEYCODE_ALT_LEFT,
+ KeyEvent.KEYCODE_EQUALS
+ ),
+ KeyGestureEvent.KEY_GESTURE_TYPE_MAGNIFIER_ZOOM_IN,
+ intArrayOf(KeyEvent.KEYCODE_EQUALS),
+ KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ ),
)
}
@@ -770,6 +794,7 @@ class KeyGestureControllerTests {
com.android.hardware.input.Flags.FLAG_KEYBOARD_A11Y_SLOW_KEYS_FLAG,
com.android.hardware.input.Flags.FLAG_KEYBOARD_A11Y_STICKY_KEYS_FLAG,
com.android.hardware.input.Flags.FLAG_KEYBOARD_A11Y_MOUSE_KEYS,
+ com.android.hardware.input.Flags.FLAG_ENABLE_TALKBACK_AND_MAGNIFIER_KEY_GESTURES,
com.android.window.flags.Flags.FLAG_ENABLE_MOVE_TO_NEXT_DISPLAY_SHORTCUT,
com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS
)
@@ -787,6 +812,7 @@ class KeyGestureControllerTests {
com.android.hardware.input.Flags.FLAG_KEYBOARD_A11Y_SLOW_KEYS_FLAG,
com.android.hardware.input.Flags.FLAG_KEYBOARD_A11Y_STICKY_KEYS_FLAG,
com.android.hardware.input.Flags.FLAG_KEYBOARD_A11Y_MOUSE_KEYS,
+ com.android.hardware.input.Flags.FLAG_ENABLE_TALKBACK_AND_MAGNIFIER_KEY_GESTURES,
com.android.window.flags.Flags.FLAG_ENABLE_MOVE_TO_NEXT_DISPLAY_SHORTCUT,
com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS
)
@@ -995,11 +1021,28 @@ class KeyGestureControllerTests {
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR)
),
+ TestData(
+ "LOCK -> Lock Screen",
+ intArrayOf(KeyEvent.KEYCODE_LOCK),
+ KeyGestureEvent.KEY_GESTURE_TYPE_LOCK_SCREEN,
+ intArrayOf(KeyEvent.KEYCODE_LOCK),
+ 0,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ ),
+ TestData(
+ "FULLSCREEN -> Maximizes a task to fit the screen",
+ intArrayOf(KeyEvent.KEYCODE_FULLSCREEN),
+ KeyGestureEvent.KEY_GESTURE_TYPE_MAXIMIZE_FREEFORM_WINDOW,
+ intArrayOf(KeyEvent.KEYCODE_FULLSCREEN),
+ 0,
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ ),
)
}
@Test
@Parameters(method = "systemKeysTestArguments")
+ @EnableFlags(com.android.hardware.input.Flags.FLAG_ENABLE_NEW_25Q2_KEYCODES)
fun testSystemKeys(test: TestData) {
setupKeyGestureController()
testKeyGestureInternal(test)
@@ -1029,6 +1072,9 @@ class KeyGestureControllerTests {
KeyEvent.KEYCODE_STYLUS_BUTTON_SECONDARY,
KeyEvent.KEYCODE_STYLUS_BUTTON_TERTIARY,
KeyEvent.KEYCODE_STYLUS_BUTTON_TAIL,
+ KeyEvent.KEYCODE_DO_NOT_DISTURB,
+ KeyEvent.KEYCODE_LOCK,
+ KeyEvent.KEYCODE_FULLSCREEN
)
val handler = KeyGestureHandler { _, _ -> false }