summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java19
-rw-r--r--apct-tests/perftests/surfaceflinger/AndroidManifest.xml4
-rw-r--r--apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java161
-rw-r--r--apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java36
-rw-r--r--cmds/idmap2/idmap2d/Idmap2Service.cpp6
-rw-r--r--cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl1
-rw-r--r--cmds/idmap2/include/idmap2/FabricatedOverlay.h6
-rw-r--r--cmds/idmap2/include/idmap2/ResourceContainer.h2
-rw-r--r--cmds/idmap2/include/idmap2/ResourceMapping.h3
-rw-r--r--cmds/idmap2/include/idmap2/ResourceUtils.h5
-rw-r--r--cmds/idmap2/libidmap2/FabricatedOverlay.cpp50
-rw-r--r--cmds/idmap2/libidmap2/ResourceContainer.cpp6
-rw-r--r--cmds/idmap2/libidmap2/ResourceMapping.cpp6
-rw-r--r--cmds/idmap2/libidmap2/proto/fabricated_v1.proto1
-rw-r--r--cmds/idmap2/tests/FabricatedOverlayTests.cpp64
-rw-r--r--cmds/idmap2/tests/IdmapTests.cpp6
-rw-r--r--cmds/idmap2/tests/ResourceMappingTests.cpp6
-rw-r--r--config/preloaded-classes-denylist1
-rw-r--r--core/api/current.txt1
-rw-r--r--core/api/system-current.txt3
-rw-r--r--core/api/test-current.txt6
-rw-r--r--core/java/android/app/AppOpsManager.java1
-rw-r--r--core/java/android/app/NotificationChannelGroup.java21
-rw-r--r--core/java/android/companion/CompanionDeviceManager.java16
-rw-r--r--core/java/android/companion/ICompanionDeviceManager.aidl2
-rw-r--r--core/java/android/content/om/FabricatedOverlay.java44
-rw-r--r--core/java/android/content/pm/PackageManager.java2
-rw-r--r--core/java/android/inputmethodservice/IInputMethodWrapper.java11
-rw-r--r--core/java/android/inputmethodservice/InputMethodService.java54
-rw-r--r--core/java/android/os/BatteryStats.java13
-rw-r--r--core/java/android/os/IUserManager.aidl1
-rw-r--r--core/java/android/os/PowerManager.java38
-rw-r--r--core/java/android/os/UserManager.java15
-rw-r--r--core/java/android/provider/Settings.java8
-rw-r--r--core/java/android/view/IWindowManager.aidl5
-rw-r--r--core/java/android/view/InsetsState.java14
-rw-r--r--core/java/android/view/WindowLayout.java18
-rw-r--r--core/java/android/view/inputmethod/InputMethod.java7
-rw-r--r--core/java/android/widget/LinearLayout.java64
-rw-r--r--core/java/android/widget/RatingBar.java29
-rw-r--r--core/java/android/widget/TextView.java24
-rw-r--r--core/java/android/window/TransitionInfo.java11
-rw-r--r--core/java/com/android/internal/app/ResolverActivity.java15
-rw-r--r--core/java/com/android/internal/app/chooser/DisplayResolveInfo.java9
-rw-r--r--core/java/com/android/internal/inputmethod/IInputMethod.aidl3
-rw-r--r--core/java/com/android/internal/jank/InteractionJankMonitor.java21
-rw-r--r--core/jni/com_android_internal_os_LongArrayMultiStateCounter.cpp46
-rw-r--r--core/jni/com_android_internal_os_LongMultiStateCounter.cpp38
-rw-r--r--core/proto/android/os/tombstone.proto30
-rw-r--r--core/res/Android.bp60
-rw-r--r--core/res/AndroidManifest.xml2
-rw-r--r--core/res/res/values/config.xml3
-rw-r--r--core/res/res/values/strings.xml9
-rw-r--r--core/res/res/values/symbols.xml2
-rw-r--r--core/tests/coretests/src/com/android/internal/os/LongArrayMultiStateCounterTest.java12
-rw-r--r--core/tests/coretests/src/com/android/internal/os/LongMultiStateCounterTest.java12
-rw-r--r--data/etc/services.core.protolog.json12
-rw-r--r--graphics/java/android/graphics/text/LineBreakConfig.java6
-rw-r--r--libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java142
-rw-r--r--libs/WindowManager/Jetpack/src/androidx/window/util/BaseDataProducer.java44
-rw-r--r--libs/WindowManager/Jetpack/src/androidx/window/util/ExtensionHelper.java20
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java3
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java2
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java2
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java21
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java4
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskListener.java11
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java50
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/fullscreen/FullscreenTaskListener.java255
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java4
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java14
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/transition/IShellTransitions.aidl5
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java5
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java2
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/CommonAssertions.kt143
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/helpers/SplitScreenHelper.kt19
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt4
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt2
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt4
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt4
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt4
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt4
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt4
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt177
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchAppByDoubleTapDivider.kt4
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt4
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt4
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt4
-rw-r--r--packages/SettingsLib/MainSwitchPreference/res/layout-v33/settingslib_main_switch_bar.xml6
-rw-r--r--packages/SettingsLib/Spa/.idea/codeStyles/Project.xml9
-rw-r--r--packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/SettingsPagerPage.kt17
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/LogCompositions.kt39
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Pager.kt339
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/PagerState.kt318
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsDimension.kt6
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Collections.kt33
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Flows.kt58
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/Actions.kt13
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/RegularScaffold.kt28
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsPager.kt27
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffold.kt73
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsTab.kt31
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Text.kt18
-rw-r--r--packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsPagerKtTest.kt5
-rw-r--r--packages/SettingsLib/SpaPrivileged/Android.bp5
-rw-r--r--packages/SettingsLib/SpaPrivileged/res/values/strings.xml28
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListModel.kt29
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListViewModel.kt125
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppRepository.kt6
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppsRepository.kt114
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfo.kt28
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt19
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppList.kt102
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListItem.kt64
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListPage.kt86
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt15
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListModel.kt31
-rw-r--r--packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListPage.kt106
-rw-r--r--packages/SettingsLib/res/values/strings.xml15
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/dream/DreamBackend.java137
-rw-r--r--packages/SettingsLib/tests/robotests/src/com/android/settingslib/dream/DreamBackendTest.java47
-rw-r--r--packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/MainSwitchBarTest.java12
-rw-r--r--packages/SystemUI/shared/src/com/android/systemui/shared/regionsampling/RegionSamplingInstance.kt18
-rw-r--r--packages/SystemUI/src/com/android/systemui/ActivityIntentHelper.java61
-rw-r--r--packages/SystemUI/src/com/android/systemui/dreams/complication/ComplicationTypesUpdater.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/flags/Flags.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/navigationbar/gestural/EdgeBackGestureHandler.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java46
-rw-r--r--packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java89
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/SysuiStatusBarStateController.java8
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListAttachState.kt12
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java51
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java23
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java20
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/util/SysuiLifecycle.java72
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/dreams/complication/ComplicationTypesUpdaterTest.java2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/screenshot/TakeScreenshotServiceTest.kt237
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java63
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarStateControllerImplTest.kt8
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt2
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java14
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java5
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java175
-rw-r--r--services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java7
-rw-r--r--services/core/java/com/android/server/BootReceiver.java50
-rw-r--r--services/core/java/com/android/server/TelephonyRegistry.java19
-rw-r--r--services/core/java/com/android/server/am/ActivityManagerService.java77
-rw-r--r--services/core/java/com/android/server/am/BroadcastDispatcher.java4
-rw-r--r--services/core/java/com/android/server/am/BroadcastQueue.java2562
-rw-r--r--services/core/java/com/android/server/am/BroadcastQueueImpl.java1960
-rw-r--r--services/core/java/com/android/server/am/BroadcastSkipPolicy.java715
-rw-r--r--services/core/java/com/android/server/audio/AudioDeviceBroker.java4
-rw-r--r--services/core/java/com/android/server/biometrics/sensors/BiometricStateCallback.java26
-rw-r--r--services/core/java/com/android/server/broadcastradio/hal2/RadioEventLogger.java44
-rw-r--r--services/core/java/com/android/server/broadcastradio/hal2/RadioModule.java18
-rw-r--r--services/core/java/com/android/server/broadcastradio/hal2/TunerSession.java42
-rw-r--r--services/core/java/com/android/server/camera/CameraServiceProxy.java9
-rw-r--r--services/core/java/com/android/server/connectivity/Vpn.java12
-rw-r--r--services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java1
-rw-r--r--services/core/java/com/android/server/hdmi/HdmiControlService.java2
-rw-r--r--services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java13
-rw-r--r--services/core/java/com/android/server/inputmethod/InputMethodBindingController.java3
-rw-r--r--services/core/java/com/android/server/inputmethod/InputMethodManagerService.java92
-rw-r--r--services/core/java/com/android/server/location/contexthub/ContextHubEventLogger.java107
-rw-r--r--services/core/java/com/android/server/notification/PreferencesHelper.java55
-rw-r--r--services/core/java/com/android/server/om/OverlayManagerShellCommand.java15
-rw-r--r--services/core/java/com/android/server/os/NativeTombstoneManager.java11
-rw-r--r--services/core/java/com/android/server/pm/InstallPackageHelper.java4
-rw-r--r--services/core/java/com/android/server/pm/ReconcilePackageUtils.java47
-rw-r--r--services/core/java/com/android/server/pm/UserManagerService.java28
-rw-r--r--services/core/java/com/android/server/policy/SingleKeyGestureDetector.java25
-rw-r--r--services/core/java/com/android/server/power/Notifier.java3
-rw-r--r--services/core/java/com/android/server/power/PowerGroup.java27
-rw-r--r--services/core/java/com/android/server/power/PowerManagerService.java45
-rw-r--r--services/core/java/com/android/server/power/stats/BatteryStatsImpl.java11
-rw-r--r--services/core/java/com/android/server/wm/AccessibilityController.java3
-rw-r--r--services/core/java/com/android/server/wm/ActivityRecord.java7
-rw-r--r--services/core/java/com/android/server/wm/BLASTSyncEngine.java32
-rw-r--r--services/core/java/com/android/server/wm/DisplayContent.java152
-rw-r--r--services/core/java/com/android/server/wm/DisplayPolicy.java253
-rw-r--r--services/core/java/com/android/server/wm/Task.java11
-rw-r--r--services/core/java/com/android/server/wm/TaskFragment.java11
-rw-r--r--services/core/java/com/android/server/wm/Transition.java195
-rw-r--r--services/core/java/com/android/server/wm/TransitionController.java34
-rw-r--r--services/core/java/com/android/server/wm/WindowContainer.java12
-rw-r--r--services/core/java/com/android/server/wm/WindowManagerService.java32
-rw-r--r--services/core/java/com/android/server/wm/WindowOrganizerController.java2
-rw-r--r--services/core/java/com/android/server/wm/WindowState.java50
-rw-r--r--services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java15
-rw-r--r--services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java52
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/job/controllers/BatteryControllerTest.java6
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/job/controllers/ConnectivityControllerTest.java14
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java140
-rw-r--r--services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/BiometricStateCallbackTest.java10
-rw-r--r--services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java30
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java7
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/DisplayPolicyInsetsTests.java91
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/SyncEngineTests.java50
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java34
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/TransitionTests.java32
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java4
-rw-r--r--services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java7
-rw-r--r--tests/testables/tests/AndroidManifest.xml2
-rw-r--r--tests/testables/tests/AndroidTest.xml27
-rw-r--r--tools/aapt2/dump/DumpManifest.cpp16
-rw-r--r--tools/aapt2/integration-tests/DumpTest/components.apkbin84534 -> 92659 bytes
-rw-r--r--tools/aapt2/integration-tests/DumpTest/components_full_proto.txt4
-rw-r--r--tools/lint/OWNERS1
213 files changed, 7885 insertions, 4453 deletions
diff --git a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
index d5c386fc5368..a65205500651 100644
--- a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
+++ b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
@@ -424,7 +424,7 @@ public class UserLifecycleTests {
final int userId = createManagedProfile();
// Start the profile initially, then stop it. Similar to setQuietModeEnabled.
startUserInBackgroundAndWaitForUnlock(userId);
- stopUser(userId, true);
+ stopUserAfterWaitingForBroadcastIdle(userId, true);
mRunner.resumeTiming();
Log.i(TAG, "Starting timer");
@@ -479,7 +479,7 @@ public class UserLifecycleTests {
installPreexistingApp(userId, DUMMY_PACKAGE_NAME);
startUserInBackgroundAndWaitForUnlock(userId);
startApp(userId, DUMMY_PACKAGE_NAME);
- stopUser(userId, true);
+ stopUserAfterWaitingForBroadcastIdle(userId, true);
SystemClock.sleep(1_000); // 1 second cool-down before re-starting profile.
mRunner.resumeTiming();
Log.i(TAG, "Starting timer");
@@ -676,6 +676,19 @@ public class UserLifecycleTests {
return success[0];
}
+ /**
+ * Waits for broadcast idle before stopping a user, to prevent timeouts on stop user.
+ * Stopping a user heavily depends on broadcast queue, and that gets crowded after user creation
+ * or user switches, which leads to a timeout on stopping user and cause the tests to be flaky.
+ * Do not call this method while timing is on. i.e. between mRunner.resumeTiming() and
+ * mRunner.pauseTiming(). Otherwise it would cause the test results to be spiky.
+ */
+ private void stopUserAfterWaitingForBroadcastIdle(int userId, boolean force)
+ throws RemoteException {
+ ShellHelper.runShellCommand("am wait-for-broadcast-idle");
+ stopUser(userId, force);
+ }
+
private void stopUser(int userId, boolean force) throws RemoteException {
final CountDownLatch latch = new CountDownLatch(1);
mIam.stopUser(userId, force /* force */, new IStopUserCallback.Stub() {
@@ -711,7 +724,7 @@ public class UserLifecycleTests {
attestTrue("Didn't switch back to user, " + origUser, origUser == mAm.getCurrentUser());
if (stopNewUser) {
- stopUser(testUser, true);
+ stopUserAfterWaitingForBroadcastIdle(testUser, true);
attestFalse("Failed to stop user " + testUser, mAm.isUserRunning(testUser));
}
diff --git a/apct-tests/perftests/surfaceflinger/AndroidManifest.xml b/apct-tests/perftests/surfaceflinger/AndroidManifest.xml
index c908d6ae4cff..26f25863f055 100644
--- a/apct-tests/perftests/surfaceflinger/AndroidManifest.xml
+++ b/apct-tests/perftests/surfaceflinger/AndroidManifest.xml
@@ -16,6 +16,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.perftests.surfaceflinger">
+ <!-- permission needed to write perfetto trace and read/write simpleperf report -->
+ <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
<application android:label="SurfaceFlingerPerfTests">
<uses-library android:name="android.test.runner" />
<activity android:name="android.surfaceflinger.SurfaceFlingerTestActivity"
diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java
index 3ca1ad58955d..9d364782a57f 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java
@@ -16,6 +16,7 @@
package com.android.server.job.controllers;
+import static android.text.format.DateUtils.DAY_IN_MILLIS;
import static android.text.format.DateUtils.HOUR_IN_MILLIS;
import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
@@ -31,6 +32,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.job.JobInfo;
import android.content.Context;
+import android.content.pm.PackageManager;
import android.os.Looper;
import android.os.UserHandle;
import android.provider.DeviceConfig;
@@ -80,31 +82,26 @@ public final class FlexibilityController extends StateController {
private static final long NO_LIFECYCLE_END = Long.MAX_VALUE;
/**
- * Keeps track of what flexible constraints are satisfied at the moment.
- * Is updated by the other controllers.
- */
- @VisibleForTesting
- @GuardedBy("mLock")
- int mSatisfiedFlexibleConstraints;
-
- /** Hard cutoff to remove flexible constraints. */
- private long mDeadlineProximityLimitMs =
- FcConfig.DEFAULT_DEADLINE_PROXIMITY_LIMIT_MS;
-
- /**
* The default deadline that all flexible constraints should be dropped by if a job lacks
* a deadline.
*/
private long mFallbackFlexibilityDeadlineMs =
FcConfig.DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_MS;
- @GuardedBy("mLock")
+ private long mRescheduledJobDeadline = FcConfig.DEFAULT_RESCHEDULED_JOB_DEADLINE_MS;
+ private long mMaxRescheduledDeadline = FcConfig.DEFAULT_MAX_RESCHEDULED_DEADLINE_MS;
+
@VisibleForTesting
+ @GuardedBy("mLock")
boolean mFlexibilityEnabled = FcConfig.DEFAULT_FLEXIBILITY_ENABLED;
private long mMinTimeBetweenFlexibilityAlarmsMs =
FcConfig.DEFAULT_MIN_TIME_BETWEEN_FLEXIBILITY_ALARMS_MS;
+ /** Hard cutoff to remove flexible constraints. */
+ private long mDeadlineProximityLimitMs =
+ FcConfig.DEFAULT_DEADLINE_PROXIMITY_LIMIT_MS;
+
/**
* The percent of a job's lifecycle to drop number of required constraints.
* mPercentToDropConstraints[i] denotes that at x% of a Jobs lifecycle,
@@ -113,6 +110,17 @@ public final class FlexibilityController extends StateController {
private int[] mPercentToDropConstraints;
@VisibleForTesting
+ boolean mDeviceSupportsFlexConstraints;
+
+ /**
+ * Keeps track of what flexible constraints are satisfied at the moment.
+ * Is updated by the other controllers.
+ */
+ @VisibleForTesting
+ @GuardedBy("mLock")
+ int mSatisfiedFlexibleConstraints;
+
+ @VisibleForTesting
@GuardedBy("mLock")
final FlexibilityTracker mFlexibilityTracker;
@VisibleForTesting
@@ -120,7 +128,6 @@ public final class FlexibilityController extends StateController {
final FlexibilityAlarmQueue mFlexibilityAlarmQueue;
@VisibleForTesting
final FcConfig mFcConfig;
-
@VisibleForTesting
final PrefetchController mPrefetchController;
@@ -168,6 +175,9 @@ public final class FlexibilityController extends StateController {
public FlexibilityController(
JobSchedulerService service, PrefetchController prefetchController) {
super(service);
+ mDeviceSupportsFlexConstraints = !mContext.getPackageManager().hasSystemFeature(
+ PackageManager.FEATURE_AUTOMOTIVE);
+ mFlexibilityEnabled &= mDeviceSupportsFlexConstraints;
mFlexibilityTracker = new FlexibilityTracker(NUM_FLEXIBLE_CONSTRAINTS);
mFcConfig = new FcConfig();
mFlexibilityAlarmQueue = new FlexibilityAlarmQueue(
@@ -187,10 +197,14 @@ public final class FlexibilityController extends StateController {
@GuardedBy("mLock")
public void maybeStartTrackingJobLocked(JobStatus js, JobStatus lastJob) {
if (js.hasFlexibilityConstraint()) {
- mFlexibilityTracker.add(js);
- js.setTrackingController(JobStatus.TRACKING_FLEXIBILITY);
final long nowElapsed = sElapsedRealtimeClock.millis();
+ if (!mDeviceSupportsFlexConstraints) {
+ js.setFlexibilityConstraintSatisfied(nowElapsed, true);
+ return;
+ }
js.setFlexibilityConstraintSatisfied(nowElapsed, isFlexibilitySatisfiedLocked(js));
+ mFlexibilityTracker.add(js);
+ js.setTrackingController(JobStatus.TRACKING_FLEXIBILITY);
mFlexibilityAlarmQueue.scheduleDropNumConstraintsAlarm(js, nowElapsed);
}
}
@@ -321,6 +335,12 @@ public final class FlexibilityController extends StateController {
// There is no deadline and no estimated launch time.
return NO_LIFECYCLE_END;
}
+ if (js.getNumFailures() > 1) {
+ // Number of failures will not equal one as per restriction in JobStatus constructor.
+ return earliest + Math.min(
+ (long) Math.scalb(mRescheduledJobDeadline, js.getNumFailures() - 2),
+ mMaxRescheduledDeadline);
+ }
return js.getLatestRunTimeElapsed() == JobStatus.NO_LATEST_RUNTIME
? earliest + mFallbackFlexibilityDeadlineMs : js.getLatestRunTimeElapsed();
}
@@ -340,7 +360,6 @@ public final class FlexibilityController extends StateController {
return percentInTime;
}
- /** The elapsed time that marks when the next constraint should be dropped. */
@VisibleForTesting
@ElapsedRealtimeLong
@GuardedBy("mLock")
@@ -351,7 +370,6 @@ public final class FlexibilityController extends StateController {
}
/** The elapsed time that marks when the next constraint should be dropped. */
- @VisibleForTesting
@ElapsedRealtimeLong
@GuardedBy("mLock")
long getNextConstraintDropTimeElapsedLocked(JobStatus js, long earliest, long latest) {
@@ -406,7 +424,7 @@ public final class FlexibilityController extends StateController {
final ArraySet<JobStatus> changedJobs = new ArraySet<>();
synchronized (mLock) {
final long nowElapsed = sElapsedRealtimeClock.millis();
- for (int j = 1; j <= mFlexibilityTracker.size(); j++) {
+ for (int j = 0; j < mFlexibilityTracker.size(); j++) {
final ArraySet<JobStatus> jobs = mFlexibilityTracker
.getJobsByNumRequiredConstraints(j);
for (int i = 0; i < jobs.size(); i++) {
@@ -445,7 +463,7 @@ public final class FlexibilityController extends StateController {
FlexibilityTracker(int numFlexibleConstraints) {
mTrackedJobs = new ArrayList<>();
- for (int i = 0; i < numFlexibleConstraints; i++) {
+ for (int i = 0; i <= numFlexibleConstraints; i++) {
mTrackedJobs.add(new ArraySet<JobStatus>());
}
}
@@ -457,15 +475,15 @@ public final class FlexibilityController extends StateController {
Slog.wtfStack(TAG, "Asked for a larger number of constraints than exists.");
return null;
}
- return mTrackedJobs.get(numRequired - 1);
+ return mTrackedJobs.get(numRequired);
}
/** adds a JobStatus object based on number of required flexible constraints. */
public void add(JobStatus js) {
- if (js.getNumRequiredFlexibleConstraints() <= 0) {
+ if (js.getNumRequiredFlexibleConstraints() < 0) {
return;
}
- mTrackedJobs.get(js.getNumRequiredFlexibleConstraints() - 1).add(js);
+ mTrackedJobs.get(js.getNumRequiredFlexibleConstraints()).add(js);
}
/** Removes a JobStatus object. */
@@ -473,7 +491,7 @@ public final class FlexibilityController extends StateController {
if (js.getNumRequiredFlexibleConstraints() == 0) {
return;
}
- mTrackedJobs.get(js.getNumRequiredFlexibleConstraints() - 1).remove(js);
+ mTrackedJobs.get(js.getNumRequiredFlexibleConstraints()).remove(js);
}
public void resetJobNumDroppedConstraints(JobStatus js, long nowElapsed) {
@@ -498,21 +516,15 @@ public final class FlexibilityController extends StateController {
/**
* Adjusts number of required flexible constraints and sorts it into the tracker.
* Returns false if the job status's number of flexible constraints is now 0.
- * Jobs with 0 required flexible constraints are removed from the tracker.
*/
- public boolean adjustJobsRequiredConstraints(JobStatus js, int n, long nowElapsed) {
- if (n == 0) {
- return false;
- }
- remove(js);
- js.adjustNumRequiredFlexibleConstraints(n);
- js.setFlexibilityConstraintSatisfied(nowElapsed, isFlexibilitySatisfiedLocked(js));
- if (js.getNumRequiredFlexibleConstraints() <= 0) {
- maybeStopTrackingJobLocked(js, null, false);
- return false;
+ public boolean adjustJobsRequiredConstraints(JobStatus js, int adjustBy, long nowElapsed) {
+ if (adjustBy != 0) {
+ remove(js);
+ js.adjustNumRequiredFlexibleConstraints(adjustBy);
+ js.setFlexibilityConstraintSatisfied(nowElapsed, isFlexibilitySatisfiedLocked(js));
+ add(js);
}
- add(js);
- return true;
+ return js.getNumRequiredFlexibleConstraints() > 0;
}
public int size() {
@@ -531,6 +543,8 @@ public final class FlexibilityController extends StateController {
js.printUniqueId(pw);
pw.print(" from ");
UserHandle.formatUid(pw, js.getSourceUid());
+ pw.print(" Num Required Constraints: ");
+ pw.print(js.getNumRequiredFlexibleConstraints());
pw.println();
}
}
@@ -551,20 +565,24 @@ public final class FlexibilityController extends StateController {
}
public void scheduleDropNumConstraintsAlarm(JobStatus js, long nowElapsed) {
- long nextTimeElapsed;
synchronized (mLock) {
final long earliest = getLifeCycleBeginningElapsedLocked(js);
final long latest = getLifeCycleEndElapsedLocked(js, earliest);
- nextTimeElapsed = getNextConstraintDropTimeElapsedLocked(js, earliest, latest);
+ final long nextTimeElapsed =
+ getNextConstraintDropTimeElapsedLocked(js, earliest, latest);
+
+ if (latest - nowElapsed < mDeadlineProximityLimitMs) {
+ mFlexibilityTracker.adjustJobsRequiredConstraints(js,
+ -js.getNumRequiredFlexibleConstraints(), nowElapsed);
+ return;
+ }
if (nextTimeElapsed == NO_LIFECYCLE_END) {
// There is no known or estimated next time to drop a constraint.
removeAlarmForKey(js);
return;
}
-
if (latest - nextTimeElapsed < mDeadlineProximityLimitMs) {
- mFlexibilityTracker.adjustJobsRequiredConstraints(
- js, -js.getNumRequiredFlexibleConstraints(), nowElapsed);
+ addAlarm(js, latest - mDeadlineProximityLimitMs);
return;
}
addAlarm(js, nextTimeElapsed);
@@ -579,20 +597,8 @@ public final class FlexibilityController extends StateController {
for (int i = 0; i < expired.size(); i++) {
JobStatus js = expired.valueAt(i);
boolean wasFlexibilitySatisfied = js.isConstraintSatisfied(CONSTRAINT_FLEXIBLE);
-
- final long earliest = getLifeCycleBeginningElapsedLocked(js);
- final long latest = getLifeCycleEndElapsedLocked(js, earliest);
-
- if (latest - nowElapsed < mDeadlineProximityLimitMs) {
- mFlexibilityTracker.adjustJobsRequiredConstraints(js,
- -js.getNumRequiredFlexibleConstraints(), nowElapsed);
- } else {
- long nextTimeElapsed =
- getNextConstraintDropTimeElapsedLocked(js, earliest, latest);
- if (mFlexibilityTracker.adjustJobsRequiredConstraints(js, -1, nowElapsed)
- && nextTimeElapsed != NO_LIFECYCLE_END) {
- mFlexibilityAlarmQueue.addAlarm(js, nextTimeElapsed);
- }
+ if (mFlexibilityTracker.adjustJobsRequiredConstraints(js, -1, nowElapsed)) {
+ scheduleDropNumConstraintsAlarm(js, nowElapsed);
}
if (wasFlexibilitySatisfied != js.isConstraintSatisfied(CONSTRAINT_FLEXIBLE)) {
changedJobs.add(js);
@@ -619,6 +625,10 @@ public final class FlexibilityController extends StateController {
FC_CONFIG_PREFIX + "min_alarm_time_flexibility_ms";
static final String KEY_PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS =
FC_CONFIG_PREFIX + "percents_to_drop_num_flexible_constraints";
+ static final String KEY_MAX_RESCHEDULED_DEADLINE_MS =
+ FC_CONFIG_PREFIX + "max_rescheduled_deadline_ms";
+ static final String KEY_RESCHEDULED_JOB_DEADLINE_MS =
+ FC_CONFIG_PREFIX + "rescheduled_job_deadline_ms";
private static final boolean DEFAULT_FLEXIBILITY_ENABLED = false;
@VisibleForTesting
@@ -628,6 +638,8 @@ public final class FlexibilityController extends StateController {
private static final long DEFAULT_MIN_TIME_BETWEEN_FLEXIBILITY_ALARMS_MS = MINUTE_IN_MILLIS;
@VisibleForTesting
final int[] DEFAULT_PERCENT_TO_DROP_FLEXIBLE_CONSTRAINTS = {50, 60, 70, 80};
+ private static final long DEFAULT_RESCHEDULED_JOB_DEADLINE_MS = HOUR_IN_MILLIS;
+ private static final long DEFAULT_MAX_RESCHEDULED_DEADLINE_MS = 5 * DAY_IN_MILLIS;
/**
* If false the controller will not track new jobs
@@ -643,13 +655,18 @@ public final class FlexibilityController extends StateController {
/** The percentages of a jobs' lifecycle to drop the number of required constraints. */
public int[] PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS =
DEFAULT_PERCENT_TO_DROP_FLEXIBLE_CONSTRAINTS;
+ /** Initial fallback flexible deadline for rescheduled jobs. */
+ public long RESCHEDULED_JOB_DEADLINE_MS = DEFAULT_RESCHEDULED_JOB_DEADLINE_MS;
+ /** The max deadline for rescheduled jobs. */
+ public long MAX_RESCHEDULED_DEADLINE_MS = DEFAULT_MAX_RESCHEDULED_DEADLINE_MS;
@GuardedBy("mLock")
public void processConstantLocked(@NonNull DeviceConfig.Properties properties,
@NonNull String key) {
switch (key) {
case KEY_FLEXIBILITY_ENABLED:
- FLEXIBILITY_ENABLED = properties.getBoolean(key, DEFAULT_FLEXIBILITY_ENABLED);
+ FLEXIBILITY_ENABLED = properties.getBoolean(key, DEFAULT_FLEXIBILITY_ENABLED)
+ && mDeviceSupportsFlexConstraints;
if (mFlexibilityEnabled != FLEXIBILITY_ENABLED) {
mFlexibilityEnabled = FLEXIBILITY_ENABLED;
mShouldReevaluateConstraints = true;
@@ -662,6 +679,22 @@ public final class FlexibilityController extends StateController {
}
}
break;
+ case KEY_RESCHEDULED_JOB_DEADLINE_MS:
+ RESCHEDULED_JOB_DEADLINE_MS =
+ properties.getLong(key, DEFAULT_RESCHEDULED_JOB_DEADLINE_MS);
+ if (mRescheduledJobDeadline != RESCHEDULED_JOB_DEADLINE_MS) {
+ mRescheduledJobDeadline = RESCHEDULED_JOB_DEADLINE_MS;
+ mShouldReevaluateConstraints = true;
+ }
+ break;
+ case KEY_MAX_RESCHEDULED_DEADLINE_MS:
+ MAX_RESCHEDULED_DEADLINE_MS =
+ properties.getLong(key, DEFAULT_MAX_RESCHEDULED_DEADLINE_MS);
+ if (mMaxRescheduledDeadline != MAX_RESCHEDULED_DEADLINE_MS) {
+ mMaxRescheduledDeadline = MAX_RESCHEDULED_DEADLINE_MS;
+ mShouldReevaluateConstraints = true;
+ }
+ break;
case KEY_DEADLINE_PROXIMITY_LIMIT:
DEADLINE_PROXIMITY_LIMIT_MS =
properties.getLong(key, DEFAULT_DEADLINE_PROXIMITY_LIMIT_MS);
@@ -733,6 +766,14 @@ public final class FlexibilityController extends StateController {
pw.increaseIndent();
pw.print(KEY_FLEXIBILITY_ENABLED, FLEXIBILITY_ENABLED).println();
+ pw.print(KEY_DEADLINE_PROXIMITY_LIMIT, DEADLINE_PROXIMITY_LIMIT_MS).println();
+ pw.print(KEY_FALLBACK_FLEXIBILITY_DEADLINE, FALLBACK_FLEXIBILITY_DEADLINE_MS).println();
+ pw.print(KEY_MIN_TIME_BETWEEN_FLEXIBILITY_ALARMS_MS,
+ MIN_TIME_BETWEEN_FLEXIBILITY_ALARMS_MS).println();
+ pw.print(KEY_PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS,
+ PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS).println();
+ pw.print(KEY_RESCHEDULED_JOB_DEADLINE_MS, RESCHEDULED_JOB_DEADLINE_MS).println();
+ pw.print(KEY_MAX_RESCHEDULED_DEADLINE_MS, MAX_RESCHEDULED_DEADLINE_MS).println();
pw.decreaseIndent();
}
@@ -748,9 +789,15 @@ public final class FlexibilityController extends StateController {
@GuardedBy("mLock")
public void dumpControllerStateLocked(IndentingPrintWriter pw, Predicate<JobStatus> predicate) {
pw.println("# Constraints Satisfied: " + Integer.bitCount(mSatisfiedFlexibleConstraints));
+ pw.print("Satisfied Flexible Constraints: ");
+ JobStatus.dumpConstraints(pw, mSatisfiedFlexibleConstraints);
+ pw.println();
pw.println();
mFlexibilityTracker.dump(pw, predicate);
+ pw.println();
+ mFlexibilityAlarmQueue.dump(pw);
+ pw.println();
mFcConfig.dump(pw);
}
}
diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java
index 4ce6b32166c1..4320db09aef5 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java
@@ -572,8 +572,11 @@ public final class JobStatus {
(latestRunTimeElapsedMillis - earliestRunTimeElapsedMillis)
>= MIN_WINDOW_FOR_FLEXIBILITY_MS;
+ // The first time a job is rescheduled it will not be subject to flexible constraints.
+ // Otherwise, every consecutive reschedule increases a jobs' flexibility deadline.
if (!isRequestedExpeditedJob()
&& satisfiesMinWindowException
+ && numFailures != 1
&& lacksSomeFlexibleConstraints) {
mNumRequiredFlexibleConstraints =
NUM_SYSTEM_WIDE_FLEXIBLE_CONSTRAINTS + (mPreferUnmetered ? 1 : 0);
@@ -1928,35 +1931,38 @@ public final class JobStatus {
proto.end(token);
}
- void dumpConstraints(PrintWriter pw, int constraints) {
- if ((constraints&CONSTRAINT_CHARGING) != 0) {
+ static void dumpConstraints(PrintWriter pw, int constraints) {
+ if ((constraints & CONSTRAINT_CHARGING) != 0) {
pw.print(" CHARGING");
}
- if ((constraints& CONSTRAINT_BATTERY_NOT_LOW) != 0) {
+ if ((constraints & CONSTRAINT_BATTERY_NOT_LOW) != 0) {
pw.print(" BATTERY_NOT_LOW");
}
- if ((constraints& CONSTRAINT_STORAGE_NOT_LOW) != 0) {
+ if ((constraints & CONSTRAINT_STORAGE_NOT_LOW) != 0) {
pw.print(" STORAGE_NOT_LOW");
}
- if ((constraints&CONSTRAINT_TIMING_DELAY) != 0) {
+ if ((constraints & CONSTRAINT_TIMING_DELAY) != 0) {
pw.print(" TIMING_DELAY");
}
- if ((constraints&CONSTRAINT_DEADLINE) != 0) {
+ if ((constraints & CONSTRAINT_DEADLINE) != 0) {
pw.print(" DEADLINE");
}
- if ((constraints&CONSTRAINT_IDLE) != 0) {
+ if ((constraints & CONSTRAINT_IDLE) != 0) {
pw.print(" IDLE");
}
- if ((constraints&CONSTRAINT_CONNECTIVITY) != 0) {
+ if ((constraints & CONSTRAINT_CONNECTIVITY) != 0) {
pw.print(" CONNECTIVITY");
}
- if ((constraints&CONSTRAINT_CONTENT_TRIGGER) != 0) {
+ if ((constraints & CONSTRAINT_FLEXIBLE) != 0) {
+ pw.print(" FLEXIBILITY");
+ }
+ if ((constraints & CONSTRAINT_CONTENT_TRIGGER) != 0) {
pw.print(" CONTENT_TRIGGER");
}
- if ((constraints&CONSTRAINT_DEVICE_NOT_DOZING) != 0) {
+ if ((constraints & CONSTRAINT_DEVICE_NOT_DOZING) != 0) {
pw.print(" DEVICE_NOT_DOZING");
}
- if ((constraints&CONSTRAINT_BACKGROUND_NOT_RESTRICTED) != 0) {
+ if ((constraints & CONSTRAINT_BACKGROUND_NOT_RESTRICTED) != 0) {
pw.print(" BACKGROUND_NOT_RESTRICTED");
}
if ((constraints & CONSTRAINT_PREFETCH) != 0) {
@@ -2242,6 +2248,14 @@ public final class JobStatus {
((requiredConstraints | CONSTRAINT_WITHIN_QUOTA | CONSTRAINT_TARE_WEALTH)
& ~satisfiedConstraints));
pw.println();
+ if (hasFlexibilityConstraint()) {
+ pw.print("Num Required Flexible constraints: ");
+ pw.print(getNumRequiredFlexibleConstraints());
+ pw.println();
+ pw.print("Num Dropped Flexible constraints: ");
+ pw.print(getNumDroppedFlexibleConstraints());
+ pw.println();
+ }
pw.println("Constraint history:");
pw.increaseIndent();
diff --git a/cmds/idmap2/idmap2d/Idmap2Service.cpp b/cmds/idmap2/idmap2d/Idmap2Service.cpp
index 073d987f5dad..083bbf01bf5b 100644
--- a/cmds/idmap2/idmap2d/Idmap2Service.cpp
+++ b/cmds/idmap2/idmap2d/Idmap2Service.cpp
@@ -235,9 +235,11 @@ Status Idmap2Service::createFabricatedOverlay(
for (const auto& res : overlay.entries) {
if (res.dataType == Res_value::TYPE_STRING) {
- builder.SetResourceValue(res.resourceName, res.dataType, res.stringData.value());
+ builder.SetResourceValue(res.resourceName, res.dataType, res.stringData.value(),
+ res.configuration.value_or(std::string()));
} else {
- builder.SetResourceValue(res.resourceName, res.dataType, res.data);
+ builder.SetResourceValue(res.resourceName, res.dataType, res.data,
+ res.configuration.value_or(std::string()));
}
}
diff --git a/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl b/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl
index a6824da8c424..c773e112997d 100644
--- a/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl
+++ b/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl
@@ -24,4 +24,5 @@ parcelable FabricatedOverlayInternalEntry {
int dataType;
int data;
@nullable @utf8InCpp String stringData;
+ @nullable @utf8InCpp String configuration;
} \ No newline at end of file
diff --git a/cmds/idmap2/include/idmap2/FabricatedOverlay.h b/cmds/idmap2/include/idmap2/FabricatedOverlay.h
index 2fc4d43b798a..05b0618131c9 100644
--- a/cmds/idmap2/include/idmap2/FabricatedOverlay.h
+++ b/cmds/idmap2/include/idmap2/FabricatedOverlay.h
@@ -39,10 +39,11 @@ struct FabricatedOverlay {
Builder& SetOverlayable(const std::string& name);
Builder& SetResourceValue(const std::string& resource_name, uint8_t data_type,
- uint32_t data_value);
+ uint32_t data_value, const std::string& configuration);
Builder& SetResourceValue(const std::string& resource_name, uint8_t data_type,
- const std::string& data_string_value);
+ const std::string& data_string_value,
+ const std::string& configuration);
WARN_UNUSED Result<FabricatedOverlay> Build();
@@ -52,6 +53,7 @@ struct FabricatedOverlay {
DataType data_type;
DataValue data_value;
std::string data_string_value;
+ std::string configuration;
};
std::string package_name_;
diff --git a/cmds/idmap2/include/idmap2/ResourceContainer.h b/cmds/idmap2/include/idmap2/ResourceContainer.h
index c3ba4640bd77..2452ff0784ce 100644
--- a/cmds/idmap2/include/idmap2/ResourceContainer.h
+++ b/cmds/idmap2/include/idmap2/ResourceContainer.h
@@ -66,7 +66,7 @@ struct OverlayData {
struct Value {
std::string resource_name;
- std::variant<ResourceIdValue, TargetValue> value;
+ std::variant<ResourceIdValue, TargetValueWithConfig> value;
};
struct InlineStringPoolData {
diff --git a/cmds/idmap2/include/idmap2/ResourceMapping.h b/cmds/idmap2/include/idmap2/ResourceMapping.h
index 5a0a384f75a3..21862a3635d5 100644
--- a/cmds/idmap2/include/idmap2/ResourceMapping.h
+++ b/cmds/idmap2/include/idmap2/ResourceMapping.h
@@ -69,7 +69,8 @@ class ResourceMapping {
// If `allow_rewriting_` is true, then the overlay-to-target map will be populated if the target
// resource id is mapped to an overlay resource id.
Result<Unit> AddMapping(ResourceId target_resource,
- const std::variant<OverlayData::ResourceIdValue, TargetValue>& value);
+ const std::variant<OverlayData::ResourceIdValue,
+ TargetValueWithConfig>& value);
TargetResourceMap target_map_;
OverlayResourceMap overlay_map_;
diff --git a/cmds/idmap2/include/idmap2/ResourceUtils.h b/cmds/idmap2/include/idmap2/ResourceUtils.h
index 414aa064ada7..8ec749602c4a 100644
--- a/cmds/idmap2/include/idmap2/ResourceUtils.h
+++ b/cmds/idmap2/include/idmap2/ResourceUtils.h
@@ -43,6 +43,11 @@ struct TargetValue {
std::string data_string_value;
};
+struct TargetValueWithConfig {
+ TargetValue value;
+ std::string config;
+};
+
namespace utils {
// Returns whether the Res_value::data_type represents a dynamic or regular resource reference.
diff --git a/cmds/idmap2/libidmap2/FabricatedOverlay.cpp b/cmds/idmap2/libidmap2/FabricatedOverlay.cpp
index 5bbe08524c18..bde9b0be4361 100644
--- a/cmds/idmap2/libidmap2/FabricatedOverlay.cpp
+++ b/cmds/idmap2/libidmap2/FabricatedOverlay.cpp
@@ -70,19 +70,22 @@ FabricatedOverlay::Builder& FabricatedOverlay::Builder::SetOverlayable(const std
}
FabricatedOverlay::Builder& FabricatedOverlay::Builder::SetResourceValue(
- const std::string& resource_name, uint8_t data_type, uint32_t data_value) {
- entries_.emplace_back(Entry{resource_name, data_type, data_value, ""});
+ const std::string& resource_name, uint8_t data_type, uint32_t data_value,
+ const std::string& configuration) {
+ entries_.emplace_back(Entry{resource_name, data_type, data_value, "", configuration});
return *this;
}
FabricatedOverlay::Builder& FabricatedOverlay::Builder::SetResourceValue(
- const std::string& resource_name, uint8_t data_type, const std::string& data_string_value) {
- entries_.emplace_back(Entry{resource_name, data_type, 0, data_string_value});
+ const std::string& resource_name, uint8_t data_type, const std::string& data_string_value,
+ const std::string& configuration) {
+ entries_.emplace_back(Entry{resource_name, data_type, 0, data_string_value, configuration});
return *this;
}
Result<FabricatedOverlay> FabricatedOverlay::Builder::Build() {
- using EntryMap = std::map<std::string, TargetValue>;
+ using ConfigMap = std::map<std::string, TargetValue>;
+ using EntryMap = std::map<std::string, ConfigMap>;
using TypeMap = std::map<std::string, EntryMap>;
using PackageMap = std::map<std::string, TypeMap>;
PackageMap package_map;
@@ -123,11 +126,16 @@ Result<FabricatedOverlay> FabricatedOverlay::Builder::Build() {
auto entry = type->second.find(entry_name.to_string());
if (entry == type->second.end()) {
- entry = type->second.insert(std::make_pair(entry_name.to_string(), TargetValue())).first;
+ entry = type->second.insert(std::make_pair(entry_name.to_string(), ConfigMap())).first;
}
- entry->second = TargetValue{
- res_entry.data_type, res_entry.data_value, res_entry.data_string_value};
+ auto value = entry->second.find(res_entry.configuration);
+ if (value == entry->second.end()) {
+ value = entry->second.insert(std::make_pair(res_entry.configuration, TargetValue())).first;
+ }
+
+ value->second = TargetValue{res_entry.data_type, res_entry.data_value,
+ res_entry.data_string_value};
}
pb::FabricatedOverlay overlay_pb;
@@ -145,15 +153,18 @@ Result<FabricatedOverlay> FabricatedOverlay::Builder::Build() {
type_pb->set_name(type.first);
for (auto& entry : type.second) {
- auto entry_pb = type_pb->add_entries();
- entry_pb->set_name(entry.first);
- pb::ResourceValue* value = entry_pb->mutable_res_value();
- value->set_data_type(entry.second.data_type);
- if (entry.second.data_type == Res_value::TYPE_STRING) {
- auto ref = string_pool.MakeRef(entry.second.data_string_value);
- value->set_data_value(ref.index());
- } else {
- value->set_data_value(entry.second.data_value);
+ for (const auto& value: entry.second) {
+ auto entry_pb = type_pb->add_entries();
+ entry_pb->set_name(entry.first);
+ entry_pb->set_configuration(value.first);
+ pb::ResourceValue* pb_value = entry_pb->mutable_res_value();
+ pb_value->set_data_type(value.second.data_type);
+ if (value.second.data_type == Res_value::TYPE_STRING) {
+ auto ref = string_pool.MakeRef(value.second.data_string_value);
+ pb_value->set_data_value(ref.index());
+ } else {
+ pb_value->set_data_value(value.second.data_value);
+ }
}
}
}
@@ -330,8 +341,9 @@ Result<OverlayData> FabContainer::GetOverlayData(const OverlayManifestInfo& info
entry.name().c_str());
const auto& res_value = entry.res_value();
result.pairs.emplace_back(OverlayData::Value{
- name, TargetValue{.data_type = static_cast<uint8_t>(res_value.data_type()),
- .data_value = res_value.data_value()}});
+ name, TargetValueWithConfig{.config = entry.configuration(), .value = TargetValue{
+ .data_type = static_cast<uint8_t>(res_value.data_type()),
+ .data_value = res_value.data_value()}}});
}
}
}
diff --git a/cmds/idmap2/libidmap2/ResourceContainer.cpp b/cmds/idmap2/libidmap2/ResourceContainer.cpp
index a62472c8f11e..0e3590486c6f 100644
--- a/cmds/idmap2/libidmap2/ResourceContainer.cpp
+++ b/cmds/idmap2/libidmap2/ResourceContainer.cpp
@@ -226,8 +226,10 @@ Result<OverlayData> CreateResourceMapping(ResourceId id, const ZipAssetsProvider
*target_resource, OverlayData::ResourceIdValue{overlay_resource->data, rewrite_id}});
} else {
overlay_data.pairs.emplace_back(
- OverlayData::Value{*target_resource, TargetValue{.data_type = overlay_resource->dataType,
- .data_value = overlay_resource->data}});
+ OverlayData::Value{*target_resource, TargetValueWithConfig{
+ .config = std::string(),
+ .value = TargetValue{.data_type = overlay_resource->dataType,
+ .data_value = overlay_resource->data}}});
}
}
diff --git a/cmds/idmap2/libidmap2/ResourceMapping.cpp b/cmds/idmap2/libidmap2/ResourceMapping.cpp
index 3bbbf248c87d..8ebe5aa46e73 100644
--- a/cmds/idmap2/libidmap2/ResourceMapping.cpp
+++ b/cmds/idmap2/libidmap2/ResourceMapping.cpp
@@ -160,7 +160,7 @@ Result<ResourceMapping> ResourceMapping::FromContainers(const TargetResourceCont
Result<Unit> ResourceMapping::AddMapping(
ResourceId target_resource,
- const std::variant<OverlayData::ResourceIdValue, TargetValue>& value) {
+ const std::variant<OverlayData::ResourceIdValue, TargetValueWithConfig>& value) {
if (target_map_.find(target_resource) != target_map_.end()) {
return Error(R"(target resource id "0x%08x" mapped to multiple values)", target_resource);
}
@@ -176,8 +176,8 @@ Result<Unit> ResourceMapping::AddMapping(
overlay_map_.insert(std::make_pair(overlay_resource->overlay_id, target_resource));
}
} else {
- auto overlay_value = std::get<TargetValue>(value);
- target_map_.insert(std::make_pair(target_resource, overlay_value));
+ auto overlay_value = std::get<TargetValueWithConfig>(value);
+ target_map_.insert(std::make_pair(target_resource, overlay_value.value));
}
return Unit{};
diff --git a/cmds/idmap2/libidmap2/proto/fabricated_v1.proto b/cmds/idmap2/libidmap2/proto/fabricated_v1.proto
index a392b2b6d856..c7a79b31e151 100644
--- a/cmds/idmap2/libidmap2/proto/fabricated_v1.proto
+++ b/cmds/idmap2/libidmap2/proto/fabricated_v1.proto
@@ -46,6 +46,7 @@ message ResourceEntry {
oneof value {
ResourceValue res_value = 2;
}
+ string configuration = 3;
}
message ResourceValue {
diff --git a/cmds/idmap2/tests/FabricatedOverlayTests.cpp b/cmds/idmap2/tests/FabricatedOverlayTests.cpp
index 91331ca1cc76..e804c879ee82 100644
--- a/cmds/idmap2/tests/FabricatedOverlayTests.cpp
+++ b/cmds/idmap2/tests/FabricatedOverlayTests.cpp
@@ -43,10 +43,17 @@ TEST(FabricatedOverlayTests, OverlayInfo) {
TEST(FabricatedOverlayTests, SetResourceValue) {
auto overlay =
FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "com.example.target")
- .SetResourceValue("com.example.target:integer/int1", Res_value::TYPE_INT_DEC, 1U)
- .SetResourceValue("com.example.target.split:integer/int2", Res_value::TYPE_INT_DEC, 2U)
- .SetResourceValue("string/int3", Res_value::TYPE_REFERENCE, 0x7f010000)
- .SetResourceValue("com.example.target:string/string1", Res_value::TYPE_STRING, "foobar")
+ .SetResourceValue(
+ "com.example.target:integer/int1", Res_value::TYPE_INT_DEC, 1U, "port")
+ .SetResourceValue(
+ "com.example.target.split:integer/int2", Res_value::TYPE_INT_DEC, 2U, "land")
+ .SetResourceValue(
+ "string/int3", Res_value::TYPE_REFERENCE, 0x7f010000, "xxhdpi-v7")
+ .SetResourceValue(
+ "com.example.target:string/string1",
+ Res_value::TYPE_STRING,
+ "foobar",
+ "en-rUS-normal-xxhdpi-v21")
.Build();
ASSERT_TRUE(overlay);
auto container = FabricatedOverlayContainer::FromOverlay(std::move(*overlay));
@@ -66,44 +73,48 @@ TEST(FabricatedOverlayTests, SetResourceValue) {
auto& it = pairs->pairs[0];
ASSERT_EQ("com.example.target:integer/int1", it.resource_name);
- auto entry = std::get_if<TargetValue>(&it.value);
+ auto entry = std::get_if<TargetValueWithConfig>(&it.value);
ASSERT_NE(nullptr, entry);
- ASSERT_EQ(1U, entry->data_value);
- ASSERT_EQ(Res_value::TYPE_INT_DEC, entry->data_type);
+ ASSERT_EQ(1U, entry->value.data_value);
+ ASSERT_EQ(Res_value::TYPE_INT_DEC, entry->value.data_type);
+ ASSERT_EQ("port", entry->config);
it = pairs->pairs[1];
ASSERT_EQ("com.example.target:string/int3", it.resource_name);
- entry = std::get_if<TargetValue>(&it.value);
+ entry = std::get_if<TargetValueWithConfig>(&it.value);
ASSERT_NE(nullptr, entry);
- ASSERT_EQ(0x7f010000, entry->data_value);
- ASSERT_EQ(Res_value::TYPE_REFERENCE, entry->data_type);
+ ASSERT_EQ(0x7f010000, entry->value.data_value);
+ ASSERT_EQ(Res_value::TYPE_REFERENCE, entry->value.data_type);
+ ASSERT_EQ("xxhdpi-v7", entry->config);
it = pairs->pairs[2];
ASSERT_EQ("com.example.target:string/string1", it.resource_name);
- entry = std::get_if<TargetValue>(&it.value);
+ entry = std::get_if<TargetValueWithConfig>(&it.value);
ASSERT_NE(nullptr, entry);
- ASSERT_EQ(Res_value::TYPE_STRING, entry->data_type);
- ASSERT_EQ(std::string("foobar"), string_pool.string8At(entry->data_value).value_or(""));
+ ASSERT_EQ(Res_value::TYPE_STRING, entry->value.data_type);
+ ASSERT_EQ(std::string("foobar"), string_pool.string8At(entry->value.data_value).value_or(""));
+ ASSERT_EQ("en-rUS-normal-xxhdpi-v21", entry->config);
it = pairs->pairs[3];
ASSERT_EQ("com.example.target.split:integer/int2", it.resource_name);
- entry = std::get_if<TargetValue>(&it.value);
+ entry = std::get_if<TargetValueWithConfig>(&it.value);
ASSERT_NE(nullptr, entry);
- ASSERT_EQ(2U, entry->data_value);
- ASSERT_EQ(Res_value::TYPE_INT_DEC, entry->data_type);
+ ASSERT_EQ(2U, entry->value.data_value);
+ ASSERT_EQ(Res_value::TYPE_INT_DEC, entry->value.data_type);
+ ASSERT_EQ("land", entry->config);
}
TEST(FabricatedOverlayTests, SetResourceValueBadArgs) {
{
auto builder =
FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "com.example.target")
- .SetResourceValue("int1", Res_value::TYPE_INT_DEC, 1U);
+ .SetResourceValue("int1", Res_value::TYPE_INT_DEC, 1U, "");
ASSERT_FALSE(builder.Build());
}
{
auto builder =
FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "com.example.target")
- .SetResourceValue("com.example.target:int2", Res_value::TYPE_INT_DEC, 1U);
+ .SetResourceValue("com.example.target:int2", Res_value::TYPE_INT_DEC, 1U, "");
ASSERT_FALSE(builder.Build());
}
}
@@ -112,8 +123,9 @@ TEST(FabricatedOverlayTests, SerializeAndDeserialize) {
auto overlay =
FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "com.example.target")
.SetOverlayable("TestResources")
- .SetResourceValue("com.example.target:integer/int1", Res_value::TYPE_INT_DEC, 1U)
- .SetResourceValue("com.example.target:string/string1", Res_value::TYPE_STRING, "foobar")
+ .SetResourceValue("com.example.target:integer/int1", Res_value::TYPE_INT_DEC, 1U, "")
+ .SetResourceValue(
+ "com.example.target:string/string1", Res_value::TYPE_STRING, "foobar", "")
.Build();
ASSERT_TRUE(overlay);
TemporaryFile tf;
@@ -142,17 +154,17 @@ TEST(FabricatedOverlayTests, SerializeAndDeserialize) {
auto& it = pairs->pairs[0];
ASSERT_EQ("com.example.target:integer/int1", it.resource_name);
- auto entry = std::get_if<TargetValue>(&it.value);
+ auto entry = std::get_if<TargetValueWithConfig>(&it.value);
ASSERT_NE(nullptr, entry);
- EXPECT_EQ(1U, entry->data_value);
- EXPECT_EQ(Res_value::TYPE_INT_DEC, entry->data_type);
+ EXPECT_EQ(1U, entry->value.data_value);
+ EXPECT_EQ(Res_value::TYPE_INT_DEC, entry->value.data_type);
it = pairs->pairs[1];
ASSERT_EQ("com.example.target:string/string1", it.resource_name);
- entry = std::get_if<TargetValue>(&it.value);
+ entry = std::get_if<TargetValueWithConfig>(&it.value);
ASSERT_NE(nullptr, entry);
- ASSERT_EQ(Res_value::TYPE_STRING, entry->data_type);
- ASSERT_EQ(std::string("foobar"), string_pool.string8At(entry->data_value).value_or(""));
+ ASSERT_EQ(Res_value::TYPE_STRING, entry->value.data_type);
+ ASSERT_EQ(std::string("foobar"), string_pool.string8At(entry->value.data_value).value_or(""));
}
} // namespace android::idmap2
diff --git a/cmds/idmap2/tests/IdmapTests.cpp b/cmds/idmap2/tests/IdmapTests.cpp
index a3799f98c90c..ee9a424b3050 100644
--- a/cmds/idmap2/tests/IdmapTests.cpp
+++ b/cmds/idmap2/tests/IdmapTests.cpp
@@ -261,9 +261,9 @@ TEST(IdmapTests, FabricatedOverlay) {
auto frro = FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "test.target")
.SetOverlayable("TestResources")
- .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U)
- .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000)
- .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar")
+ .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U, "")
+ .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000, "")
+ .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar", "")
.Build();
ASSERT_TRUE(frro);
diff --git a/cmds/idmap2/tests/ResourceMappingTests.cpp b/cmds/idmap2/tests/ResourceMappingTests.cpp
index c05abcf31532..ca9a444bcb05 100644
--- a/cmds/idmap2/tests/ResourceMappingTests.cpp
+++ b/cmds/idmap2/tests/ResourceMappingTests.cpp
@@ -194,9 +194,9 @@ TEST(ResourceMappingTests, InlineResources) {
TEST(ResourceMappingTests, FabricatedOverlay) {
auto frro = FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "test.target")
.SetOverlayable("TestResources")
- .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U)
- .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000)
- .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar")
+ .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U, "")
+ .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000, "")
+ .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar", "")
.Build();
ASSERT_TRUE(frro);
diff --git a/config/preloaded-classes-denylist b/config/preloaded-classes-denylist
index 02f2df6167a5..502d8c6dadb1 100644
--- a/config/preloaded-classes-denylist
+++ b/config/preloaded-classes-denylist
@@ -9,3 +9,4 @@ android.net.rtp.AudioGroup
android.net.rtp.AudioStream
android.net.rtp.RtpStream
java.util.concurrent.ThreadLocalRandom
+com.android.internal.jank.InteractionJankMonitor$InstanceHolder
diff --git a/core/api/current.txt b/core/api/current.txt
index 795c43056d04..317f8eb5c6b5 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -32264,6 +32264,7 @@ package android.os {
method @NonNull @RequiresPermission(anyOf={"android.permission.MANAGE_USERS", "android.permission.QUERY_USERS", "android.permission.INTERACT_ACROSS_USERS"}, conditional=true) public android.content.pm.UserProperties getUserProperties(@NonNull android.os.UserHandle);
method public android.os.Bundle getUserRestrictions();
method @RequiresPermission(anyOf={"android.permission.MANAGE_USERS", "android.permission.INTERACT_ACROSS_USERS"}, conditional=true) public android.os.Bundle getUserRestrictions(android.os.UserHandle);
+ method @NonNull @RequiresPermission(anyOf={"android.permission.MANAGE_USERS", "android.permission.INTERACT_ACROSS_USERS"}) public java.util.List<android.os.UserHandle> getVisibleUsers();
method public boolean hasUserRestriction(String);
method public boolean isDemoUser();
method public static boolean isHeadlessSystemUserMode();
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index a0cc4f0d6775..2b2f2023bef6 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -320,6 +320,7 @@ package android {
field public static final String START_ACTIVITIES_FROM_BACKGROUND = "android.permission.START_ACTIVITIES_FROM_BACKGROUND";
field public static final String START_CROSS_PROFILE_ACTIVITIES = "android.permission.START_CROSS_PROFILE_ACTIVITIES";
field public static final String START_REVIEW_PERMISSION_DECISIONS = "android.permission.START_REVIEW_PERMISSION_DECISIONS";
+ field public static final String START_TASKS_FROM_RECENTS = "android.permission.START_TASKS_FROM_RECENTS";
field public static final String STATUS_BAR_SERVICE = "android.permission.STATUS_BAR_SERVICE";
field public static final String STOP_APP_SWITCHES = "android.permission.STOP_APP_SWITCHES";
field public static final String SUBSTITUTE_NOTIFICATION_APP_NAME = "android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME";
@@ -507,7 +508,7 @@ package android.app {
public class ActivityOptions {
method public int getLaunchTaskId();
- method @RequiresPermission("android.permission.START_TASKS_FROM_RECENTS") public void setLaunchTaskId(int);
+ method @RequiresPermission(android.Manifest.permission.START_TASKS_FROM_RECENTS) public void setLaunchTaskId(int);
}
public class AlarmManager {
diff --git a/core/api/test-current.txt b/core/api/test-current.txt
index fefdfd8d7b15..f45298a630cd 100644
--- a/core/api/test-current.txt
+++ b/core/api/test-current.txt
@@ -42,7 +42,6 @@ package android {
field public static final String SET_AND_VERIFY_LOCKSCREEN_CREDENTIALS = "android.permission.SET_AND_VERIFY_LOCKSCREEN_CREDENTIALS";
field public static final String SET_GAME_SERVICE = "android.permission.SET_GAME_SERVICE";
field public static final String SET_KEYBOARD_LAYOUT = "android.permission.SET_KEYBOARD_LAYOUT";
- field public static final String START_TASKS_FROM_RECENTS = "android.permission.START_TASKS_FROM_RECENTS";
field public static final String SUSPEND_APPS = "android.permission.SUSPEND_APPS";
field public static final String TEST_BIOMETRIC = "android.permission.TEST_BIOMETRIC";
field public static final String TEST_MANAGE_ROLLBACKS = "android.permission.TEST_MANAGE_ROLLBACKS";
@@ -3204,6 +3203,11 @@ package android.widget {
method public android.widget.ListView getMenuListView();
}
+ public class RatingBar extends android.widget.AbsSeekBar {
+ field public static final String PLURALS_MAX = "max";
+ field public static final String PLURALS_RATING = "rating";
+ }
+
public class Spinner extends android.widget.AbsSpinner implements android.content.DialogInterface.OnClickListener {
method public boolean isPopupShowing();
}
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index d6b90a2792a9..2a5916dfb6a8 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -1906,7 +1906,6 @@ public class AppOpsManager {
OP_SCHEDULE_EXACT_ALARM,
OP_MANAGE_MEDIA,
OP_TURN_SCREEN_ON,
- OP_GET_USAGE_STATS,
};
static final AppOpInfo[] sAppOpInfos = new AppOpInfo[]{
diff --git a/core/java/android/app/NotificationChannelGroup.java b/core/java/android/app/NotificationChannelGroup.java
index 807bd5764cba..2b245aae915f 100644
--- a/core/java/android/app/NotificationChannelGroup.java
+++ b/core/java/android/app/NotificationChannelGroup.java
@@ -20,7 +20,6 @@ import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
-import android.content.pm.ParceledListSlice;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
@@ -68,7 +67,7 @@ public final class NotificationChannelGroup implements Parcelable {
private CharSequence mName;
private String mDescription;
private boolean mBlocked;
- private ParceledListSlice<NotificationChannel> mChannels;
+ private List<NotificationChannel> mChannels = new ArrayList<>();
// Bitwise representation of fields that have been changed by the user
private int mUserLockedFields;
@@ -103,8 +102,7 @@ public final class NotificationChannelGroup implements Parcelable {
} else {
mDescription = null;
}
- mChannels = in.readParcelable(
- NotificationChannelGroup.class.getClassLoader(), ParceledListSlice.class);
+ in.readParcelableList(mChannels, NotificationChannel.class.getClassLoader(), android.app.NotificationChannel.class);
mBlocked = in.readBoolean();
mUserLockedFields = in.readInt();
}
@@ -131,7 +129,7 @@ public final class NotificationChannelGroup implements Parcelable {
} else {
dest.writeByte((byte) 0);
}
- dest.writeParcelable(mChannels, flags);
+ dest.writeParcelableList(mChannels, flags);
dest.writeBoolean(mBlocked);
dest.writeInt(mUserLockedFields);
}
@@ -161,7 +159,7 @@ public final class NotificationChannelGroup implements Parcelable {
* Returns the list of channels that belong to this group
*/
public List<NotificationChannel> getChannels() {
- return mChannels == null ? new ArrayList<>() : mChannels.getList();
+ return mChannels;
}
/**
@@ -195,8 +193,15 @@ public final class NotificationChannelGroup implements Parcelable {
/**
* @hide
*/
+ public void addChannel(NotificationChannel channel) {
+ mChannels.add(channel);
+ }
+
+ /**
+ * @hide
+ */
public void setChannels(List<NotificationChannel> channels) {
- mChannels = new ParceledListSlice<>(channels);
+ mChannels = channels;
}
/**
@@ -331,7 +336,7 @@ public final class NotificationChannelGroup implements Parcelable {
proto.write(NotificationChannelGroupProto.NAME, mName.toString());
proto.write(NotificationChannelGroupProto.DESCRIPTION, mDescription);
proto.write(NotificationChannelGroupProto.IS_BLOCKED, mBlocked);
- for (NotificationChannel channel : mChannels.getList()) {
+ for (NotificationChannel channel : mChannels) {
channel.dumpDebug(proto, NotificationChannelGroupProto.CHANNELS);
}
proto.end(token);
diff --git a/core/java/android/companion/CompanionDeviceManager.java b/core/java/android/companion/CompanionDeviceManager.java
index 8ffc6a28bef3..c1a3c1934dbb 100644
--- a/core/java/android/companion/CompanionDeviceManager.java
+++ b/core/java/android/companion/CompanionDeviceManager.java
@@ -1008,6 +1008,22 @@ public final class CompanionDeviceManager {
}
}
+ /**
+ * Checks whether the calling companion application is currently bound.
+ *
+ * @return true if application is bound, false otherwise
+ * @hide
+ */
+ @UserHandleAware
+ public boolean isCompanionApplicationBound() {
+ try {
+ return mService.isCompanionApplicationBound(
+ mContext.getOpPackageName(), mContext.getUserId());
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
private boolean checkFeaturePresent() {
boolean featurePresent = mService != null;
if (!featurePresent && DEBUG) {
diff --git a/core/java/android/companion/ICompanionDeviceManager.aidl b/core/java/android/companion/ICompanionDeviceManager.aidl
index 6e6e18765639..17e313252010 100644
--- a/core/java/android/companion/ICompanionDeviceManager.aidl
+++ b/core/java/android/companion/ICompanionDeviceManager.aidl
@@ -80,4 +80,6 @@ interface ICompanionDeviceManager {
void attachSystemDataTransport(String packageName, int userId, int associationId, in ParcelFileDescriptor fd);
void detachSystemDataTransport(String packageName, int userId, int associationId);
+
+ boolean isCompanionApplicationBound(String packageName, int userId);
}
diff --git a/core/java/android/content/om/FabricatedOverlay.java b/core/java/android/content/om/FabricatedOverlay.java
index 5efc1f9f7cca..3ca056097c1f 100644
--- a/core/java/android/content/om/FabricatedOverlay.java
+++ b/core/java/android/content/om/FabricatedOverlay.java
@@ -112,6 +112,28 @@ public class FabricatedOverlay {
* @param resourceName name of the target resource to overlay (in the form
* [package]:type/entry)
* @param dataType the data type of the new value
+ * @param value the unsigned 32 bit integer representing the new value
+ * @param configuration The string representation of the config this overlay is enabled for
+ *
+ * @see android.util.TypedValue#type
+ */
+ public Builder setResourceValue(@NonNull String resourceName, int dataType, int value,
+ String configuration) {
+ final FabricatedOverlayInternalEntry entry = new FabricatedOverlayInternalEntry();
+ entry.resourceName = resourceName;
+ entry.dataType = dataType;
+ entry.data = value;
+ entry.configuration = configuration;
+ mEntries.add(entry);
+ return this;
+ }
+
+ /**
+ * Sets the value of the fabricated overlay
+ *
+ * @param resourceName name of the target resource to overlay (in the form
+ * [package]:type/entry)
+ * @param dataType the data type of the new value
* @param value the string representing the new value
*
* @see android.util.TypedValue#type
@@ -125,6 +147,28 @@ public class FabricatedOverlay {
return this;
}
+ /**
+ * Sets the value of the fabricated overlay
+ *
+ * @param resourceName name of the target resource to overlay (in the form
+ * [package]:type/entry)
+ * @param dataType the data type of the new value
+ * @param value the string representing the new value
+ * @param configuration The string representation of the config this overlay is enabled for
+ *
+ * @see android.util.TypedValue#type
+ */
+ public Builder setResourceValue(@NonNull String resourceName, int dataType, String value,
+ String configuration) {
+ final FabricatedOverlayInternalEntry entry = new FabricatedOverlayInternalEntry();
+ entry.resourceName = resourceName;
+ entry.dataType = dataType;
+ entry.stringData = value;
+ entry.configuration = configuration;
+ mEntries.add(entry);
+ return this;
+ }
+
/** Builds an immutable fabricated overlay. */
public FabricatedOverlay build() {
final FabricatedOverlayInternal overlay = new FabricatedOverlayInternal();
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 5839b877a448..8e2a5eaff2d2 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -8065,7 +8065,7 @@ public abstract class PackageManager {
}
PackageParser.Package pkg = parser.parsePackage(apkFile, 0, false);
- if ((flagsBits & GET_SIGNATURES) != 0) {
+ if ((flagsBits & GET_SIGNATURES) != 0 || (flagsBits & GET_SIGNING_CERTIFICATES) != 0) {
PackageParser.collectCertificates(pkg, false /* skipVerify */);
}
return PackageParser.generatePackageInfo(pkg, null, (int) flagsBits, 0, 0, null,
diff --git a/core/java/android/inputmethodservice/IInputMethodWrapper.java b/core/java/android/inputmethodservice/IInputMethodWrapper.java
index 3d593872757d..05daf63fdd5d 100644
--- a/core/java/android/inputmethodservice/IInputMethodWrapper.java
+++ b/core/java/android/inputmethodservice/IInputMethodWrapper.java
@@ -81,6 +81,7 @@ class IInputMethodWrapper extends IInputMethod.Stub
private static final int DO_INIT_INK_WINDOW = 120;
private static final int DO_FINISH_STYLUS_HANDWRITING = 130;
private static final int DO_UPDATE_TOOL_TYPE = 140;
+ private static final int DO_REMOVE_STYLUS_HANDWRITING_WINDOW = 150;
final WeakReference<InputMethodServiceInternal> mTarget;
final Context mContext;
@@ -254,6 +255,10 @@ class IInputMethodWrapper extends IInputMethod.Stub
inputMethod.finishStylusHandwriting();
return;
}
+ case DO_REMOVE_STYLUS_HANDWRITING_WINDOW: {
+ inputMethod.removeStylusHandwritingWindow();
+ return;
+ }
}
Log.w(TAG, "Unhandled message code: " + msg.what);
@@ -434,4 +439,10 @@ class IInputMethodWrapper extends IInputMethod.Stub
public void finishStylusHandwriting() {
mCaller.executeOrSendMessage(mCaller.obtainMessage(DO_FINISH_STYLUS_HANDWRITING));
}
+
+ @BinderThread
+ @Override
+ public void removeStylusHandwritingWindow() {
+ mCaller.executeOrSendMessage(mCaller.obtainMessage(DO_REMOVE_STYLUS_HANDWRITING_WINDOW));
+ }
}
diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java
index c2027b136f0e..48b9b8869cae 100644
--- a/core/java/android/inputmethodservice/InputMethodService.java
+++ b/core/java/android/inputmethodservice/InputMethodService.java
@@ -621,7 +621,7 @@ public class InputMethodService extends AbstractInputMethodService {
private boolean mDestroyed;
private boolean mOnPreparedStylusHwCalled;
- /** Stylus handwriting Ink window. */
+ /** Stylus handwriting Ink window. */
private InkWindow mInkWindow;
/**
@@ -708,9 +708,6 @@ public class InputMethodService extends AbstractInputMethodService {
mConfigTracker.onInitialize(params.configChanges);
mPrivOps.set(params.privilegedOperations);
InputMethodPrivilegedOperationsRegistry.put(params.token, mPrivOps);
- if (params.stylusHandWritingSupported) {
- mInkWindow = new InkWindow(mWindow.getContext());
- }
mNavigationBarController.onNavButtonFlagsChanged(params.navigationBarFlags);
attachToken(params.token);
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
@@ -744,9 +741,6 @@ public class InputMethodService extends AbstractInputMethodService {
attachToWindowToken(token);
mToken = token;
mWindow.setToken(token);
- if (mInkWindow != null) {
- mInkWindow.setToken(token);
- }
}
/**
@@ -785,7 +779,7 @@ public class InputMethodService extends AbstractInputMethodService {
mInputConnection = null;
// free-up cached InkWindow surface on detaching from current client.
if (mInkWindow != null) {
- mInkWindow.hide(true /* remove */);
+ removeHandwritingInkWindow();
}
}
@@ -972,6 +966,7 @@ public class InputMethodService extends AbstractInputMethodService {
Log.d(TAG, "Input should have started before starting Stylus handwriting.");
return;
}
+ maybeCreateInkWindow();
if (!mOnPreparedStylusHwCalled) {
// prepare hasn't been called by Stylus HOVER.
onPrepareStylusHandwriting();
@@ -1031,12 +1026,24 @@ public class InputMethodService extends AbstractInputMethodService {
*/
@Override
public void initInkWindow() {
+ maybeCreateInkWindow();
mInkWindow.initOnly();
onPrepareStylusHandwriting();
mOnPreparedStylusHwCalled = true;
}
/**
+ * Create and attach token to Ink window if it wasn't already created.
+ */
+ private void maybeCreateInkWindow() {
+ if (mInkWindow == null) {
+ mInkWindow = new InkWindow(mWindow.getContext());
+ mInkWindow.setToken(mToken);
+ }
+ // TODO(b/243571274): set an idle-timeout after which InkWindow is removed.
+ }
+
+ /**
* {@inheritDoc}
* @hide
*/
@@ -1047,6 +1054,15 @@ public class InputMethodService extends AbstractInputMethodService {
/**
* {@inheritDoc}
+ * @hide
+ */
+ @Override
+ public void removeStylusHandwritingWindow() {
+ InputMethodService.this.removeStylusHandwritingWindow();
+ }
+
+ /**
+ * {@inheritDoc}
*/
@MainThread
@Override
@@ -2511,6 +2527,7 @@ public class InputMethodService extends AbstractInputMethodService {
mHandwritingEventReceiver.dispose();
mHandwritingEventReceiver = null;
+ // TODO(b/243571274): set an idle-timeout after which InkWindow is removed.
mInkWindow.hide(false /* remove */);
mPrivOps.resetStylusHandwriting(requestId);
@@ -2519,6 +2536,27 @@ public class InputMethodService extends AbstractInputMethodService {
}
/**
+ * Remove Stylus handwriting window.
+ * Typically, this is called when {@link InkWindow} should no longer be holding a surface in
+ * memory.
+ */
+ private void removeStylusHandwritingWindow() {
+ if (mInkWindow != null) {
+ if (mHandwritingRequestId.isPresent()) {
+ // if handwriting session is still ongoing. This shouldn't happen.
+ finishStylusHandwriting();
+ }
+ removeHandwritingInkWindow();
+ }
+ }
+
+ private void removeHandwritingInkWindow() {
+ mInkWindow.hide(true /* remove */);
+ mInkWindow.destroy();
+ mInkWindow = null;
+ }
+
+ /**
* Sets the duration after which an ongoing stylus handwriting session that hasn't received new
* {@link MotionEvent}s will time out and {@link #finishStylusHandwriting()} will be called.
*
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index 9d05cec06d01..09a52e452f9a 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -955,7 +955,16 @@ public abstract class BatteryStats {
public static final int NUM_WIFI_BATCHED_SCAN_BINS = 5;
- public static final int NUM_USER_ACTIVITY_TYPES = PowerManager.USER_ACTIVITY_EVENT_MAX + 1;
+ /**
+ * Note that these must match the constants in android.os.PowerManager.
+ * Also, if the user activity types change, the BatteryStatsImpl.VERSION must
+ * also be bumped.
+ */
+ static final String[] USER_ACTIVITY_TYPES = {
+ "other", "button", "touch", "accessibility", "attention"
+ };
+
+ public static final int NUM_USER_ACTIVITY_TYPES = USER_ACTIVITY_TYPES.length;
public abstract void noteUserActivityLocked(int type);
public abstract boolean hasUserActivity();
@@ -6159,7 +6168,7 @@ public abstract class BatteryStats {
}
sb.append(val);
sb.append(" ");
- sb.append(PowerManager.userActivityEventToString(i));
+ sb.append(Uid.USER_ACTIVITY_TYPES[i]);
}
}
if (hasData) {
diff --git a/core/java/android/os/IUserManager.aidl b/core/java/android/os/IUserManager.aidl
index fa6b1189f1da..88649cbf9e42 100644
--- a/core/java/android/os/IUserManager.aidl
+++ b/core/java/android/os/IUserManager.aidl
@@ -129,6 +129,7 @@ interface IUserManager {
boolean isUserRunning(int userId);
boolean isUserForeground(int userId);
boolean isUserVisible(int userId);
+ List<UserHandle> getVisibleUsers();
boolean isUserNameSet(int userId);
boolean hasRestrictedProfiles(int userId);
boolean requestQuietModeEnabled(String callingPackage, boolean enableQuietMode, int userId, in IntentSender target, int flags);
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index a3a3e3f80f3d..01b75d104e5e 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -348,44 +348,6 @@ public final class PowerManager {
public static final int USER_ACTIVITY_EVENT_DEVICE_STATE = 6;
/**
- * @hide
- */
- public static final int USER_ACTIVITY_EVENT_MAX = USER_ACTIVITY_EVENT_DEVICE_STATE;
-
- /**
- * @hide
- */
- @IntDef(prefix = { "USER_ACTIVITY_EVENT_" }, value = {
- USER_ACTIVITY_EVENT_OTHER,
- USER_ACTIVITY_EVENT_BUTTON,
- USER_ACTIVITY_EVENT_TOUCH,
- USER_ACTIVITY_EVENT_ACCESSIBILITY,
- USER_ACTIVITY_EVENT_ATTENTION,
- USER_ACTIVITY_EVENT_FACE_DOWN,
- USER_ACTIVITY_EVENT_DEVICE_STATE,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface UserActivityEvent{}
-
- /**
- *
- * Convert the user activity event to a string for debugging purposes.
- * @hide
- */
- public static String userActivityEventToString(@UserActivityEvent int userActivityEvent) {
- switch (userActivityEvent) {
- case USER_ACTIVITY_EVENT_OTHER: return "other";
- case USER_ACTIVITY_EVENT_BUTTON: return "button";
- case USER_ACTIVITY_EVENT_TOUCH: return "touch";
- case USER_ACTIVITY_EVENT_ACCESSIBILITY: return "accessibility";
- case USER_ACTIVITY_EVENT_ATTENTION: return "attention";
- case USER_ACTIVITY_EVENT_FACE_DOWN: return "faceDown";
- case USER_ACTIVITY_EVENT_DEVICE_STATE: return "deviceState";
- default: return Integer.toString(userActivityEvent);
- }
- }
-
- /**
* User activity flag: If already dimmed, extend the dim timeout
* but do not brighten. This flag is useful for keeping the screen on
* a little longer without causing a visible change such as when
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index 738f9c9c4f13..f6aaee8e3de0 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -2886,6 +2886,21 @@ public class UserManager {
}
/**
+ * Gets the visible users (as defined by {@link #isUserVisible()}.
+ *
+ * @return visible users at the moment.
+ */
+ @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS,
+ Manifest.permission.INTERACT_ACROSS_USERS})
+ public @NonNull List<UserHandle> getVisibleUsers() {
+ try {
+ return mService.getVisibleUsers();
+ } catch (RemoteException re) {
+ throw re.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Return whether the context user is running in an "unlocked" state.
* <p>
* On devices with direct boot, a user is unlocked only after they've
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 8a50e79e8598..14598d558caa 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -9187,14 +9187,12 @@ public final class Settings {
public static final String SCREENSAVER_DEFAULT_COMPONENT = "screensaver_default_component";
/**
- * The complications that are enabled to be shown over the screensaver by the user. Holds
- * a comma separated list of
- * {@link com.android.settingslib.dream.DreamBackend.ComplicationType}.
+ * Whether complications are enabled to be shown over the screensaver by the user.
*
* @hide
*/
- public static final String SCREENSAVER_ENABLED_COMPLICATIONS =
- "screensaver_enabled_complications";
+ public static final String SCREENSAVER_COMPLICATIONS_ENABLED =
+ "screensaver_complications_enabled";
/**
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index 8aa113dfc8e6..229de31ddcba 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -413,11 +413,6 @@ interface IWindowManager
boolean hasNavigationBar(int displayId);
/**
- * Get the position of the nav bar
- */
- int getNavBarPosition(int displayId);
-
- /**
* Lock the device immediately with the specified options (can be null).
*/
@UnsupportedAppUsage(maxTargetSdk = 30, trackingBug = 170729553)
diff --git a/core/java/android/view/InsetsState.java b/core/java/android/view/InsetsState.java
index 9f426a176a08..45d28da73c6b 100644
--- a/core/java/android/view/InsetsState.java
+++ b/core/java/android/view/InsetsState.java
@@ -351,6 +351,20 @@ public class InsetsState implements Parcelable {
return insets;
}
+ // TODO: Remove this once the task bar is treated as navigation bar.
+ public Insets calculateInsetsWithInternalTypes(Rect frame, @InternalInsetsType int[] types,
+ boolean ignoreVisibility) {
+ Insets insets = Insets.NONE;
+ for (int i = types.length - 1; i >= 0; i--) {
+ InsetsSource source = mSources[types[i]];
+ if (source == null) {
+ continue;
+ }
+ insets = Insets.max(source.calculateInsets(frame, ignoreVisibility), insets);
+ }
+ return insets;
+ }
+
public Insets calculateInsets(Rect frame, @InsetsType int types,
InsetsVisibilities overrideVisibilities) {
Insets insets = Insets.NONE;
diff --git a/core/java/android/view/WindowLayout.java b/core/java/android/view/WindowLayout.java
index 57a0330e3c18..5ed9d2f90a72 100644
--- a/core/java/android/view/WindowLayout.java
+++ b/core/java/android/view/WindowLayout.java
@@ -118,11 +118,11 @@ public class WindowLayout {
}
if (cutoutMode == LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES) {
if (displayFrame.width() < displayFrame.height()) {
- displayCutoutSafeExceptMaybeBars.top = Integer.MIN_VALUE;
- displayCutoutSafeExceptMaybeBars.bottom = Integer.MAX_VALUE;
+ displayCutoutSafeExceptMaybeBars.top = MIN_Y;
+ displayCutoutSafeExceptMaybeBars.bottom = MAX_Y;
} else {
- displayCutoutSafeExceptMaybeBars.left = Integer.MIN_VALUE;
- displayCutoutSafeExceptMaybeBars.right = Integer.MAX_VALUE;
+ displayCutoutSafeExceptMaybeBars.left = MIN_X;
+ displayCutoutSafeExceptMaybeBars.right = MAX_X;
}
}
final boolean layoutInsetDecor = (attrs.flags & FLAG_LAYOUT_INSET_DECOR) != 0;
@@ -132,23 +132,23 @@ public class WindowLayout {
final Insets systemBarsInsets = state.calculateInsets(
displayFrame, WindowInsets.Type.systemBars(), requestedVisibilities);
if (systemBarsInsets.left > 0) {
- displayCutoutSafeExceptMaybeBars.left = Integer.MIN_VALUE;
+ displayCutoutSafeExceptMaybeBars.left = MIN_X;
}
if (systemBarsInsets.top > 0) {
- displayCutoutSafeExceptMaybeBars.top = Integer.MIN_VALUE;
+ displayCutoutSafeExceptMaybeBars.top = MIN_Y;
}
if (systemBarsInsets.right > 0) {
- displayCutoutSafeExceptMaybeBars.right = Integer.MAX_VALUE;
+ displayCutoutSafeExceptMaybeBars.right = MAX_X;
}
if (systemBarsInsets.bottom > 0) {
- displayCutoutSafeExceptMaybeBars.bottom = Integer.MAX_VALUE;
+ displayCutoutSafeExceptMaybeBars.bottom = MAX_Y;
}
}
if (type == TYPE_INPUT_METHOD) {
final InsetsSource navSource = state.peekSource(ITYPE_NAVIGATION_BAR);
if (navSource != null && navSource.calculateInsets(displayFrame, true).bottom > 0) {
// The IME can always extend under the bottom cutout if the navbar is there.
- displayCutoutSafeExceptMaybeBars.bottom = Integer.MAX_VALUE;
+ displayCutoutSafeExceptMaybeBars.bottom = MAX_Y;
}
}
final boolean attachedInParent = attachedWindowFrame != null && !layoutInScreen;
diff --git a/core/java/android/view/inputmethod/InputMethod.java b/core/java/android/view/inputmethod/InputMethod.java
index bfe6ae6447d0..978bfc7af60d 100644
--- a/core/java/android/view/inputmethod/InputMethod.java
+++ b/core/java/android/view/inputmethod/InputMethod.java
@@ -410,4 +410,11 @@ public interface InputMethod {
// intentionally empty
}
+ /**
+ * Remove stylus handwriting window.
+ * @hide
+ */
+ default void removeStylusHandwritingWindow() {
+ // intentionally empty
+ }
}
diff --git a/core/java/android/widget/LinearLayout.java b/core/java/android/widget/LinearLayout.java
index fa84407c5c4d..7314ad83bd0c 100644
--- a/core/java/android/widget/LinearLayout.java
+++ b/core/java/android/widget/LinearLayout.java
@@ -732,6 +732,10 @@ public class LinearLayout extends ViewGroup {
* @hide Pending API consideration. Currently only used internally by the system.
*/
protected boolean hasDividerBeforeChildAt(int childIndex) {
+ if (mShowDividers == SHOW_DIVIDER_NONE) {
+ // Short-circuit to save iteration over child views.
+ return false;
+ }
if (childIndex == getVirtualChildCount()) {
// Check whether the end divider should draw.
return (mShowDividers & SHOW_DIVIDER_END) != 0;
@@ -746,6 +750,24 @@ public class LinearLayout extends ViewGroup {
}
/**
+ * Determines whether or not there's a divider after a specified child index.
+ *
+ * @param childIndex Index of child to check for following divider
+ * @return true if there should be a divider after the child at childIndex
+ */
+ private boolean hasDividerAfterChildAt(int childIndex) {
+ if (mShowDividers == SHOW_DIVIDER_NONE) {
+ // Short-circuit to save iteration over child views.
+ return false;
+ }
+ if (allViewsAreGoneAfter(childIndex)) {
+ // This is the last view that's not gone, check if end divider is enabled.
+ return (mShowDividers & SHOW_DIVIDER_END) != 0;
+ }
+ return (mShowDividers & SHOW_DIVIDER_MIDDLE) != 0;
+ }
+
+ /**
* Checks whether all (virtual) child views before the given index are gone.
*/
private boolean allViewsAreGoneBefore(int childIndex) {
@@ -759,6 +781,20 @@ public class LinearLayout extends ViewGroup {
}
/**
+ * Checks whether all (virtual) child views after the given index are gone.
+ */
+ private boolean allViewsAreGoneAfter(int childIndex) {
+ final int count = getVirtualChildCount();
+ for (int i = childIndex + 1; i < count; i++) {
+ final View child = getVirtualChildAt(i);
+ if (child != null && child.getVisibility() != GONE) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
* Measures the children when the orientation of this LinearLayout is set
* to {@link #VERTICAL}.
*
@@ -1295,6 +1331,7 @@ public class LinearLayout extends ViewGroup {
if (useLargestChild &&
(widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED)) {
mTotalLength = 0;
+ nonSkippedChildCount = 0;
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
@@ -1308,6 +1345,11 @@ public class LinearLayout extends ViewGroup {
continue;
}
+ nonSkippedChildCount++;
+ if (hasDividerBeforeChildAt(i)) {
+ mTotalLength += mDividerWidth;
+ }
+
final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)
child.getLayoutParams();
if (isExactly) {
@@ -1319,6 +1361,10 @@ public class LinearLayout extends ViewGroup {
lp.leftMargin + lp.rightMargin + getNextLocationOffset(child));
}
}
+
+ if (nonSkippedChildCount > 0 && hasDividerBeforeChildAt(count)) {
+ mTotalLength += mDividerWidth;
+ }
}
// Add in our padding
@@ -1347,6 +1393,7 @@ public class LinearLayout extends ViewGroup {
maxHeight = -1;
mTotalLength = 0;
+ nonSkippedChildCount = 0;
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
@@ -1354,6 +1401,11 @@ public class LinearLayout extends ViewGroup {
continue;
}
+ nonSkippedChildCount++;
+ if (hasDividerBeforeChildAt(i)) {
+ mTotalLength += mDividerWidth;
+ }
+
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final float childWeight = lp.weight;
if (childWeight > 0) {
@@ -1423,6 +1475,10 @@ public class LinearLayout extends ViewGroup {
}
}
+ if (nonSkippedChildCount > 0 && hasDividerBeforeChildAt(count)) {
+ mTotalLength += mDividerWidth;
+ }
+
// Add in our padding
mTotalLength += mPaddingLeft + mPaddingRight;
// TODO: Should we update widthSize with the new total length?
@@ -1810,7 +1866,13 @@ public class LinearLayout extends ViewGroup {
break;
}
- if (hasDividerBeforeChildAt(childIndex)) {
+ if (isLayoutRtl) {
+ // Because rtl rendering occurs in the reverse direction, we need to check
+ // after the child rather than before (since after=left in this context)
+ if (hasDividerAfterChildAt(childIndex)) {
+ childLeft += mDividerWidth;
+ }
+ } else if (hasDividerBeforeChildAt(childIndex)) {
childLeft += mDividerWidth;
}
diff --git a/core/java/android/widget/RatingBar.java b/core/java/android/widget/RatingBar.java
index f946fe6d8314..ec0d86295f8a 100644
--- a/core/java/android/widget/RatingBar.java
+++ b/core/java/android/widget/RatingBar.java
@@ -16,17 +16,22 @@
package android.widget;
+import android.annotation.TestApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.shapes.RectShape;
import android.graphics.drawable.shapes.Shape;
import android.util.AttributeSet;
+import android.util.PluralsMessageFormatter;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.inspector.InspectableProperty;
import com.android.internal.R;
+import java.util.HashMap;
+
+
/**
* A RatingBar is an extension of SeekBar and ProgressBar that shows a rating in
* stars. The user can touch/drag or use arrow keys to set the rating when using
@@ -53,6 +58,20 @@ import com.android.internal.R;
public class RatingBar extends AbsSeekBar {
/**
+ * Key used for generating Text-to-Speech output regarding the current star rating.
+ * @hide
+ */
+ @TestApi
+ public static final String PLURALS_RATING = "rating";
+
+ /**
+ * Key used for generating Text-to-Speech output regarding the maximum star count.
+ * @hide
+ */
+ @TestApi
+ public static final String PLURALS_MAX = "max";
+
+ /**
* A callback that notifies clients when the rating has been changed. This
* includes changes that were initiated by the user through a touch gesture
* or arrow key/trackball as well as changes that were initiated
@@ -354,6 +373,16 @@ public class RatingBar extends AbsSeekBar {
if (canUserSetProgress()) {
info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_PROGRESS);
}
+
+ final float scaledMax = getMax() * getStepSize();
+ final HashMap<String, Object> params = new HashMap();
+ params.put(PLURALS_RATING, getRating());
+ params.put(PLURALS_MAX, scaledMax);
+ info.setStateDescription(PluralsMessageFormatter.format(
+ getContext().getResources(),
+ params,
+ R.string.rating_label
+ ));
}
@Override
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 1c7c5829d2bc..cd1c23cdc75f 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -4891,24 +4891,24 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener
*
* <p>Line-break style specifies the line-break strategies that can be used
* for text wrapping. The line-break style affects rule-based line breaking
- * by specifying the strictness of line-breaking rules.</p>
+ * by specifying the strictness of line-breaking rules.
*
- * <p>The following are types of line-break styles:</p>
+ * <p>The following are types of line-break styles:
* <ul>
- * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_LOOSE}</li>
- * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_NORMAL}</li>
- * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_STRICT}</li>
+ * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_LOOSE}
+ * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_NORMAL}
+ * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_STRICT}
* </ul>
*
* <p>The default line-break style is
* {@link LineBreakConfig#LINE_BREAK_STYLE_NONE}, which specifies that no
- * line-breaking rules are used.</p>
+ * line-breaking rules are used.
*
* <p>See the
* <a href="https://www.w3.org/TR/css-text-3/#line-break-property" class="external">
- * line-break property</a> for more information.</p>
+ * line-break property</a> for more information.
*
- * @param lineBreakStyle The line break style for the text.
+ * @param lineBreakStyle The line-break style for the text.
*/
public void setLineBreakStyle(@LineBreakConfig.LineBreakStyle int lineBreakStyle) {
if (mLineBreakStyle != lineBreakStyle) {
@@ -4927,17 +4927,17 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener
* <p>The line-break word style affects dictionary-based line breaking by
* providing phrase-based line-breaking opportunities. Use
* {@link LineBreakConfig#LINE_BREAK_WORD_STYLE_PHRASE} to specify
- * phrase-based line breaking.</p>
+ * phrase-based line breaking.
*
* <p>The default line-break word style is
* {@link LineBreakConfig#LINE_BREAK_WORD_STYLE_NONE}, which specifies that
- * no line-breaking word style is used.</p>
+ * no line-breaking word style is used.
*
* <p>See the
* <a href="https://www.w3.org/TR/css-text-3/#word-break-property" class="external">
- * word-break property</a> for more information.</p>
+ * word-break property</a> for more information.
*
- * @param lineBreakWordStyle The line break word style for the text.
+ * @param lineBreakWordStyle The line-break word style for the text.
*/
public void setLineBreakWordStyle(@LineBreakConfig.LineBreakWordStyle int lineBreakWordStyle) {
mUserSpeficiedLineBreakwordStyle = true;
diff --git a/core/java/android/window/TransitionInfo.java b/core/java/android/window/TransitionInfo.java
index b263b08d6abc..dc1f612534e2 100644
--- a/core/java/android/window/TransitionInfo.java
+++ b/core/java/android/window/TransitionInfo.java
@@ -119,6 +119,12 @@ public final class TransitionInfo implements Parcelable {
/** The container is going to show IME on its task after the transition. */
public static final int FLAG_WILL_IME_SHOWN = 1 << 11;
+ /** The container attaches owner profile thumbnail for cross profile animation. */
+ public static final int FLAG_CROSS_PROFILE_OWNER_THUMBNAIL = 1 << 12;
+
+ /** The container attaches work profile thumbnail for cross profile animation. */
+ public static final int FLAG_CROSS_PROFILE_WORK_THUMBNAIL = 1 << 13;
+
/** @hide */
@IntDef(prefix = { "FLAG_" }, value = {
FLAG_NONE,
@@ -508,6 +514,11 @@ public final class TransitionInfo implements Parcelable {
return mFlags;
}
+ /** Whether the given change flags has included in this change. */
+ public boolean hasFlags(@ChangeFlags int flags) {
+ return (mFlags & flags) != 0;
+ }
+
/**
* @return the bounds of the container before the change. It may be empty if the container
* is coming into existence.
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index f67e78572402..c8bc204bd9aa 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -1283,9 +1283,6 @@ public class ResolverActivity extends Activity implements
}
if (target != null) {
- if (intent != null && isLaunchingTargetInOtherProfile()) {
- prepareIntentForCrossProfileLaunch(intent);
- }
safelyStartActivity(target);
// Rely on the ActivityManager to pop up a dialog regarding app suspension
@@ -1298,15 +1295,6 @@ public class ResolverActivity extends Activity implements
return true;
}
- private void prepareIntentForCrossProfileLaunch(Intent intent) {
- intent.fixUris(UserHandle.myUserId());
- }
-
- private boolean isLaunchingTargetInOtherProfile() {
- return mMultiProfilePagerAdapter.getCurrentUserHandle().getIdentifier()
- != UserHandle.myUserId();
- }
-
@VisibleForTesting
public void safelyStartActivity(TargetInfo cti) {
// We're dispatching intents that might be coming from legacy apps, so
@@ -1513,9 +1501,6 @@ public class ResolverActivity extends Activity implements
findViewById(R.id.button_open).setOnClickListener(v -> {
Intent intent = otherProfileResolveInfo.getResolvedIntent();
- if (intent != null) {
- prepareIntentForCrossProfileLaunch(intent);
- }
safelyStartActivityAsUser(otherProfileResolveInfo,
inactiveAdapter.mResolverListController.getUserHandle());
finish();
diff --git a/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java b/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java
index 96cc5e1bd7d2..5f4a9cd5141e 100644
--- a/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java
+++ b/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java
@@ -172,12 +172,14 @@ public class DisplayResolveInfo implements TargetInfo, Parcelable {
@Override
public boolean startAsCaller(ResolverActivity activity, Bundle options, int userId) {
+ prepareIntentForCrossProfileLaunch(mResolvedIntent, userId);
activity.startActivityAsCaller(mResolvedIntent, options, false, userId);
return true;
}
@Override
public boolean startAsUser(Activity activity, Bundle options, UserHandle user) {
+ prepareIntentForCrossProfileLaunch(mResolvedIntent, user.getIdentifier());
activity.startActivityAsUser(mResolvedIntent, options, user);
return false;
}
@@ -222,6 +224,13 @@ public class DisplayResolveInfo implements TargetInfo, Parcelable {
}
};
+ private static void prepareIntentForCrossProfileLaunch(Intent intent, int targetUserId) {
+ final int currentUserId = UserHandle.myUserId();
+ if (targetUserId != currentUserId) {
+ intent.fixUris(currentUserId);
+ }
+ }
+
private DisplayResolveInfo(Parcel in) {
mDisplayLabel = in.readCharSequence();
mExtendedInfo = in.readCharSequence();
diff --git a/core/java/com/android/internal/inputmethod/IInputMethod.aidl b/core/java/com/android/internal/inputmethod/IInputMethod.aidl
index 5db2e84845f5..9182d1dc56bf 100644
--- a/core/java/com/android/internal/inputmethod/IInputMethod.aidl
+++ b/core/java/com/android/internal/inputmethod/IInputMethod.aidl
@@ -40,7 +40,6 @@ oneway interface IInputMethod {
IBinder token;
IInputMethodPrivilegedOperations privilegedOperations;
int configChanges;
- boolean stylusHandWritingSupported;
int navigationBarFlags;
}
@@ -86,4 +85,6 @@ oneway interface IInputMethod {
void initInkWindow();
void finishStylusHandwriting();
+
+ void removeStylusHandwritingWindow();
}
diff --git a/core/java/com/android/internal/jank/InteractionJankMonitor.java b/core/java/com/android/internal/jank/InteractionJankMonitor.java
index 72de78c148f8..fc4e041058b1 100644
--- a/core/java/com/android/internal/jank/InteractionJankMonitor.java
+++ b/core/java/com/android/internal/jank/InteractionJankMonitor.java
@@ -87,6 +87,7 @@ import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.UiThread;
import android.annotation.WorkerThread;
+import android.app.ActivityThread;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
@@ -292,7 +293,10 @@ public class InteractionJankMonitor {
UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__SHADE_CLEAR_ALL,
};
- private static volatile InteractionJankMonitor sInstance;
+ private static class InstanceHolder {
+ public static final InteractionJankMonitor INSTANCE =
+ new InteractionJankMonitor(new HandlerThread(DEFAULT_WORKER_NAME));
+ }
private final DeviceConfig.OnPropertiesChangedListener mPropertiesChangedListener =
this::updateProperties;
@@ -384,15 +388,7 @@ public class InteractionJankMonitor {
* @return instance of InteractionJankMonitor
*/
public static InteractionJankMonitor getInstance() {
- // Use DCL here since this method might be invoked very often.
- if (sInstance == null) {
- synchronized (InteractionJankMonitor.class) {
- if (sInstance == null) {
- sInstance = new InteractionJankMonitor(new HandlerThread(DEFAULT_WORKER_NAME));
- }
- }
- }
- return sInstance;
+ return InstanceHolder.INSTANCE;
}
/**
@@ -402,6 +398,11 @@ public class InteractionJankMonitor {
*/
@VisibleForTesting
public InteractionJankMonitor(@NonNull HandlerThread worker) {
+ // Check permission early.
+ DeviceConfig.enforceReadPermission(
+ ActivityThread.currentApplication().getApplicationContext(),
+ DeviceConfig.NAMESPACE_INTERACTION_JANK_MONITOR);
+
mRunningTrackers = new SparseArray<>();
mTimeoutActions = new SparseArray<>();
mWorker = worker;
diff --git a/core/jni/com_android_internal_os_LongArrayMultiStateCounter.cpp b/core/jni/com_android_internal_os_LongArrayMultiStateCounter.cpp
index 0ebf2dddd7eb..5b946d5c8d3a 100644
--- a/core/jni/com_android_internal_os_LongArrayMultiStateCounter.cpp
+++ b/core/jni/com_android_internal_os_LongArrayMultiStateCounter.cpp
@@ -99,12 +99,13 @@ static void throwWriteRE(JNIEnv *env, binder_status_t status) {
jniThrowRuntimeException(env, "Could not write LongArrayMultiStateCounter to Parcel");
}
-#define THROW_ON_WRITE_ERROR(expr) \
- { \
- binder_status_t status = expr; \
- if (status != STATUS_OK) { \
- throwWriteRE(env, status); \
- } \
+#define THROW_AND_RETURN_ON_WRITE_ERROR(expr) \
+ { \
+ binder_status_t status = expr; \
+ if (status != STATUS_OK) { \
+ throwWriteRE(env, status); \
+ return; \
+ } \
}
static void native_writeToParcel(JNIEnv *env, jobject self, jlong nativePtr, jobject jParcel,
@@ -114,14 +115,15 @@ static void native_writeToParcel(JNIEnv *env, jobject self, jlong nativePtr, job
ndk::ScopedAParcel parcel(AParcel_fromJavaParcel(env, jParcel));
uint16_t stateCount = counter->getStateCount();
- THROW_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), stateCount));
+ THROW_AND_RETURN_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), stateCount));
// LongArrayMultiStateCounter has at least state 0
const std::vector<uint64_t> &anyState = counter->getCount(0);
- THROW_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), anyState.size()));
+ THROW_AND_RETURN_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), anyState.size()));
for (battery::state_t state = 0; state < stateCount; state++) {
- THROW_ON_WRITE_ERROR(ndk::AParcel_writeVector(parcel.get(), counter->getCount(state)));
+ THROW_AND_RETURN_ON_WRITE_ERROR(
+ ndk::AParcel_writeVector(parcel.get(), counter->getCount(state)));
}
}
@@ -130,35 +132,37 @@ static void throwReadRE(JNIEnv *env, binder_status_t status) {
jniThrowRuntimeException(env, "Could not read LongArrayMultiStateCounter from Parcel");
}
-#define THROW_ON_READ_ERROR(expr) \
- { \
- binder_status_t status = expr; \
- if (status != STATUS_OK) { \
- throwReadRE(env, status); \
- } \
+#define THROW_AND_RETURN_ON_READ_ERROR(expr) \
+ { \
+ binder_status_t status = expr; \
+ if (status != STATUS_OK) { \
+ throwReadRE(env, status); \
+ return 0L; \
+ } \
}
static jlong native_initFromParcel(JNIEnv *env, jclass theClass, jobject jParcel) {
ndk::ScopedAParcel parcel(AParcel_fromJavaParcel(env, jParcel));
int32_t stateCount;
- THROW_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &stateCount));
+ THROW_AND_RETURN_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &stateCount));
int32_t arrayLength;
- THROW_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &arrayLength));
+ THROW_AND_RETURN_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &arrayLength));
- battery::LongArrayMultiStateCounter *counter =
- new battery::LongArrayMultiStateCounter(stateCount, std::vector<uint64_t>(arrayLength));
+ auto counter = std::make_unique<battery::LongArrayMultiStateCounter>(stateCount,
+ std::vector<uint64_t>(
+ arrayLength));
std::vector<uint64_t> value;
value.reserve(arrayLength);
for (battery::state_t state = 0; state < stateCount; state++) {
- THROW_ON_READ_ERROR(ndk::AParcel_readVector(parcel.get(), &value));
+ THROW_AND_RETURN_ON_READ_ERROR(ndk::AParcel_readVector(parcel.get(), &value));
counter->setValue(state, value);
}
- return reinterpret_cast<jlong>(counter);
+ return reinterpret_cast<jlong>(counter.release());
}
static jint native_getStateCount(jlong nativePtr) {
diff --git a/core/jni/com_android_internal_os_LongMultiStateCounter.cpp b/core/jni/com_android_internal_os_LongMultiStateCounter.cpp
index 8c69d276fe6a..1712b3a8512b 100644
--- a/core/jni/com_android_internal_os_LongMultiStateCounter.cpp
+++ b/core/jni/com_android_internal_os_LongMultiStateCounter.cpp
@@ -109,12 +109,13 @@ static void throwWriteRE(JNIEnv *env, binder_status_t status) {
jniThrowRuntimeException(env, "Could not write LongMultiStateCounter to Parcel");
}
-#define THROW_ON_WRITE_ERROR(expr) \
- { \
- binder_status_t status = expr; \
- if (status != STATUS_OK) { \
- throwWriteRE(env, status); \
- } \
+#define THROW_AND_RETURN_ON_WRITE_ERROR(expr) \
+ { \
+ binder_status_t status = expr; \
+ if (status != STATUS_OK) { \
+ throwWriteRE(env, status); \
+ return; \
+ } \
}
static void native_writeToParcel(JNIEnv *env, jobject self, jlong nativePtr, jobject jParcel,
@@ -123,10 +124,10 @@ static void native_writeToParcel(JNIEnv *env, jobject self, jlong nativePtr, job
ndk::ScopedAParcel parcel(AParcel_fromJavaParcel(env, jParcel));
uint16_t stateCount = counter->getStateCount();
- THROW_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), stateCount));
+ THROW_AND_RETURN_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), stateCount));
for (battery::state_t state = 0; state < stateCount; state++) {
- THROW_ON_WRITE_ERROR(AParcel_writeInt64(parcel.get(), counter->getCount(state)));
+ THROW_AND_RETURN_ON_WRITE_ERROR(AParcel_writeInt64(parcel.get(), counter->getCount(state)));
}
}
@@ -135,29 +136,30 @@ static void throwReadRE(JNIEnv *env, binder_status_t status) {
jniThrowRuntimeException(env, "Could not read LongMultiStateCounter from Parcel");
}
-#define THROW_ON_READ_ERROR(expr) \
- { \
- binder_status_t status = expr; \
- if (status != STATUS_OK) { \
- throwReadRE(env, status); \
- } \
+#define THROW_AND_RETURN_ON_READ_ERROR(expr) \
+ { \
+ binder_status_t status = expr; \
+ if (status != STATUS_OK) { \
+ throwReadRE(env, status); \
+ return 0L; \
+ } \
}
static jlong native_initFromParcel(JNIEnv *env, jclass theClass, jobject jParcel) {
ndk::ScopedAParcel parcel(AParcel_fromJavaParcel(env, jParcel));
int32_t stateCount;
- THROW_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &stateCount));
+ THROW_AND_RETURN_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &stateCount));
- battery::LongMultiStateCounter *counter = new battery::LongMultiStateCounter(stateCount, 0);
+ auto counter = std::make_unique<battery::LongMultiStateCounter>(stateCount, 0);
for (battery::state_t state = 0; state < stateCount; state++) {
int64_t value;
- THROW_ON_READ_ERROR(AParcel_readInt64(parcel.get(), &value));
+ THROW_AND_RETURN_ON_READ_ERROR(AParcel_readInt64(parcel.get(), &value));
counter->setValue(state, value);
}
- return reinterpret_cast<jlong>(counter);
+ return reinterpret_cast<jlong>(counter.release());
}
static jint native_getStateCount(jlong nativePtr) {
diff --git a/core/proto/android/os/tombstone.proto b/core/proto/android/os/tombstone.proto
new file mode 100644
index 000000000000..2d3b1f3ae220
--- /dev/null
+++ b/core/proto/android/os/tombstone.proto
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto2";
+
+package android.os;
+
+option java_multiple_files = true;
+
+message TombstoneWithHeadersProto {
+ // The original proto tombstone bytes.
+ // Proto located at: system/core/debuggerd/proto/tombstone.proto
+ optional bytes tombstone = 1;
+
+ // The count of dropped dropbox entries due to rate limiting.
+ optional int32 dropped_count = 2;
+} \ No newline at end of file
diff --git a/core/res/Android.bp b/core/res/Android.bp
index c42517d8a873..93ce7832824b 100644
--- a/core/res/Android.bp
+++ b/core/res/Android.bp
@@ -73,18 +73,18 @@ genrule {
":remote-color-resources-compile-colors",
],
out: ["remote-color-resources.apk"],
- cmd: "$(location aapt2) link -o $(out) --manifest $(in)"
+ cmd: "$(location aapt2) link -o $(out) --manifest $(in)",
}
genrule {
name: "remote-color-resources-arsc",
srcs: [":remote-color-resources-apk"],
out: ["res/raw/remote_views_color_resources.arsc"],
- cmd: "mkdir -p $(genDir)/remote-color-resources-arsc && "
- + "unzip -x $(in) resources.arsc -d $(genDir)/remote-color-resources-arsc && "
- + "mkdir -p $$(dirname $(out)) && "
- + "mv $(genDir)/remote-color-resources-arsc/resources.arsc $(out) && "
- + "echo 'Created $(out)'"
+ cmd: "mkdir -p $(genDir)/remote-color-resources-arsc && " +
+ "unzip -x $(in) resources.arsc -d $(genDir)/remote-color-resources-arsc && " +
+ "mkdir -p $$(dirname $(out)) && " +
+ "mv $(genDir)/remote-color-resources-arsc/resources.arsc $(out) && " +
+ "echo 'Created $(out)'",
}
genrule {
@@ -95,11 +95,11 @@ genrule {
"remote_color_resources_res/symbols.xml",
],
out: ["remote_views_color_resources.zip"],
- cmd: "INPUTS=($(in)) && "
- + "RES_DIR=$$(dirname $$(dirname $${INPUTS[0]})) && "
- + "mkdir -p $$RES_DIR/values && "
- + "cp $${INPUTS[1]} $$RES_DIR/values && "
- + "$(location soong_zip) -o $(out) -C $$RES_DIR -D $$RES_DIR"
+ cmd: "INPUTS=($(in)) && " +
+ "RES_DIR=$$(dirname $$(dirname $${INPUTS[0]})) && " +
+ "mkdir -p $$RES_DIR/values && " +
+ "cp $${INPUTS[1]} $$RES_DIR/values && " +
+ "$(location soong_zip) -o $(out) -C $$RES_DIR -D $$RES_DIR",
}
android_app {
@@ -154,31 +154,21 @@ java_genrule {
cmd: "cp $(in) $(out)",
}
-// This logic can be removed once robolectric's transition to binary resources is complete
-filegroup {
- name: "robolectric_framework_raw_res_files",
- srcs: [
- "assets/**/*",
- "res/**/*",
- ":remote-color-resources-arsc",
- ],
-}
-
// Generate a text file containing a list of permissions that non-system apps
// are allowed to obtain.
genrule {
- name: "permission-list-normal",
- out: ["permission-list-normal.txt"],
- srcs: ["AndroidManifest.xml"],
- cmd: "cat $(in) " +
- // xmllint has trouble accessing attributes under the android namespace.
- // Strip these prefixes prior to processing with xmllint.
- " | sed -r 's/android:(name|protectionLevel)/\\1/g' " +
- " | $(location xmllint) /dev/stdin --xpath " +
- " '//permission[not(contains(@protectionLevel, \"signature\"))]/@name'" +
- // The result of xmllint is name="value" pairs. Format these to just the
- // permission name, one per-line.
- " | sed -r 's/\\s*name=\\s*//g' | tr -d '\"'" +
- " > $(out)",
- tools: ["xmllint"]
+ name: "permission-list-normal",
+ out: ["permission-list-normal.txt"],
+ srcs: ["AndroidManifest.xml"],
+ cmd: "cat $(in) " +
+ // xmllint has trouble accessing attributes under the android namespace.
+ // Strip these prefixes prior to processing with xmllint.
+ " | sed -r 's/android:(name|protectionLevel)/\\1/g' " +
+ " | $(location xmllint) /dev/stdin --xpath " +
+ " '//permission[not(contains(@protectionLevel, \"signature\"))]/@name'" +
+ // The result of xmllint is name="value" pairs. Format these to just the
+ // permission name, one per-line.
+ " | sed -r 's/\\s*name=\\s*//g' | tr -d '\"'" +
+ " > $(out)",
+ tools: ["xmllint"],
}
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 3fbd7973d81f..cd518cea8d87 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -2975,7 +2975,7 @@
<permission android:name="android.permission.REAL_GET_TASKS"
android:protectionLevel="signature|privileged" />
- <!-- @TestApi Allows an application to start a task from a ActivityManager#RecentTaskInfo.
+ <!-- @SystemApi Allows an application to start a task from a ActivityManager#RecentTaskInfo.
@hide -->
<permission android:name="android.permission.START_TASKS_FROM_RECENTS"
android:protectionLevel="signature|privileged|recents" />
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index b59cf7fd3bcb..116b15051e7d 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2392,9 +2392,6 @@
<!-- The list of supported dream complications -->
<integer-array name="config_supportedDreamComplications">
</integer-array>
- <!-- The list of dream complications which should be enabled by default -->
- <integer-array name="config_dreamComplicationsEnabledByDefault">
- </integer-array>
<!-- Are we allowed to dream while not plugged in? -->
<bool name="config_dreamsEnabledOnBattery">false</bool>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 7a2c866375d2..e5b1cf9be748 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -3365,6 +3365,13 @@
<!-- Default not selected text used by accessibility for an element that can be selected or unselected. [CHAR LIMIT=NONE] -->
<string name="not_selected">not selected</string>
+ <!-- Default label text used by accessibility for ratingbars. [CHAR LIMIT=NONE] -->
+ <string name ="rating_label">{ rating, plural,
+ =1 {One star out of {max}}
+ other {# stars out of {max}}
+ }
+ </string>
+
<!-- Default state description for indeterminate progressbar. [CHAR LIMIT=NONE] -->
<string name="in_progress">in progress</string>
@@ -5752,7 +5759,7 @@
<!-- Content for the log access confirmation dialog. [CHAR LIMIT=NONE]-->
<string name="log_access_confirmation_body">Device logs record what happens on your device. Apps can use these logs to find and fix issues.\n\nSome logs may contain sensitive info, so only allow apps you trust to access all device logs.
- \n\nIf you don’t allow this app to access all device logs, it can still access its own logs. Your device manufacturer may still be able to access some logs or info on your device. Learn more
+ \n\nIf you don’t allow this app to access all device logs, it can still access its own logs. Your device manufacturer may still be able to access some logs or info on your device.
</string>
<!-- Privacy notice do not show [CHAR LIMIT=20] -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 91f9bef740a9..d7836c12e9d6 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -925,6 +925,7 @@
<java-symbol type="string" name="mobile_provisioning_apn" />
<java-symbol type="string" name="mobile_provisioning_url" />
<java-symbol type="string" name="quick_contacts_not_available" />
+ <java-symbol type="string" name="rating_label" />
<java-symbol type="string" name="reboot_to_update_package" />
<java-symbol type="string" name="reboot_to_update_prepare" />
<java-symbol type="string" name="reboot_to_update_title" />
@@ -2228,7 +2229,6 @@
<java-symbol type="string" name="config_dreamsDefaultComponent" />
<java-symbol type="bool" name="config_dreamsOnlyEnabledForSystemUser" />
<java-symbol type="array" name="config_supportedDreamComplications" />
- <java-symbol type="array" name="config_dreamComplicationsEnabledByDefault" />
<java-symbol type="array" name="config_disabledDreamComponents" />
<java-symbol type="bool" name="config_dismissDreamOnActivityStart" />
<java-symbol type="string" name="config_loggable_dream_prefix" />
diff --git a/core/tests/coretests/src/com/android/internal/os/LongArrayMultiStateCounterTest.java b/core/tests/coretests/src/com/android/internal/os/LongArrayMultiStateCounterTest.java
index 9eb4ccb2663b..a22dd1c63ddf 100644
--- a/core/tests/coretests/src/com/android/internal/os/LongArrayMultiStateCounterTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/LongArrayMultiStateCounterTest.java
@@ -18,6 +18,8 @@ package com.android.internal.os;
import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertThrows;
+
import android.os.Parcel;
import androidx.test.filters.SmallTest;
@@ -149,4 +151,14 @@ public class LongArrayMultiStateCounterTest {
container.getValues(counts);
assertThat(counts).isEqualTo(expected);
}
+
+ @Test
+ public void createFromBadParcel() {
+ // Check we don't crash the runtime if the Parcel data is bad (b/243434675).
+ Parcel parcel = Parcel.obtain();
+ parcel.writeInt(2);
+ parcel.setDataPosition(0);
+ assertThrows(RuntimeException.class,
+ () -> LongArrayMultiStateCounter.CREATOR.createFromParcel(parcel));
+ }
}
diff --git a/core/tests/coretests/src/com/android/internal/os/LongMultiStateCounterTest.java b/core/tests/coretests/src/com/android/internal/os/LongMultiStateCounterTest.java
index e717ebbc997c..fc86ebe1c10e 100644
--- a/core/tests/coretests/src/com/android/internal/os/LongMultiStateCounterTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/LongMultiStateCounterTest.java
@@ -18,6 +18,8 @@ package com.android.internal.os;
import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertThrows;
+
import android.os.Parcel;
import androidx.test.filters.SmallTest;
@@ -198,4 +200,14 @@ public class LongMultiStateCounterTest {
assertThat(newCounter.getCount(0)).isEqualTo(116);
}
+
+ @Test
+ public void createFromBadParcel() {
+ // Check we don't crash the runtime if the Parcel data is bad (b/243434675).
+ Parcel parcel = Parcel.obtain();
+ parcel.writeInt(13);
+ parcel.setDataPosition(0);
+ assertThrows(RuntimeException.class,
+ () -> LongMultiStateCounter.CREATOR.createFromParcel(parcel));
+ }
}
diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json
index 748032b9db62..6aedcd493f5c 100644
--- a/data/etc/services.core.protolog.json
+++ b/data/etc/services.core.protolog.json
@@ -2671,6 +2671,12 @@
"group": "WM_DEBUG_ANIM",
"at": "com\/android\/server\/wm\/WindowContainer.java"
},
+ "390947100": {
+ "message": "Screenshotting %s [%s]",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_WINDOW_TRANSITIONS",
+ "at": "com\/android\/server\/wm\/Transition.java"
+ },
"397382873": {
"message": "Moving to PAUSED: %s %s",
"level": "VERBOSE",
@@ -4189,6 +4195,12 @@
"group": "WM_DEBUG_FOCUS_LIGHT",
"at": "com\/android\/server\/wm\/InputMonitor.java"
},
+ "2004282287": {
+ "message": "Override sync-method for %s because seamless rotating",
+ "level": "VERBOSE",
+ "group": "WM_DEBUG_WINDOW_TRANSITIONS",
+ "at": "com\/android\/server\/wm\/Transition.java"
+ },
"2010476671": {
"message": "Animation done in %s: reportedVisible=%b okToDisplay=%b okToAnimate=%b startingDisplayed=%b",
"level": "VERBOSE",
diff --git a/graphics/java/android/graphics/text/LineBreakConfig.java b/graphics/java/android/graphics/text/LineBreakConfig.java
index 48aecd61fc19..d0327159b04d 100644
--- a/graphics/java/android/graphics/text/LineBreakConfig.java
+++ b/graphics/java/android/graphics/text/LineBreakConfig.java
@@ -28,7 +28,7 @@ import java.util.Objects;
*
* <p>See the
* <a href="https://www.w3.org/TR/css-text-3/#line-break-property" class="external">
- * line-break property</a> for more information.</p>
+ * line-break property</a> for more information.
*/
public final class LineBreakConfig {
@@ -72,7 +72,7 @@ public final class LineBreakConfig {
*
* <p>Support for this line-break word style depends on locale. If the
* current locale does not support phrase-based text wrapping, this setting
- * has no effect.</p>
+ * has no effect.
*/
public static final int LINE_BREAK_WORD_STYLE_PHRASE = 1;
@@ -194,7 +194,7 @@ public final class LineBreakConfig {
* Constructor with line-break parameters.
*
* <p>Use {@link LineBreakConfig.Builder} to create the
- * {@code LineBreakConfig} instance.</p>
+ * {@code LineBreakConfig} instance.
*/
private LineBreakConfig(@LineBreakStyle int lineBreakStyle,
@LineBreakWordStyle int lineBreakWordStyle, boolean autoPhraseBreaking) {
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java
index 6bfb16a3c22d..f24401f0cd53 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java
@@ -20,21 +20,26 @@ import static android.view.Display.DEFAULT_DISPLAY;
import static androidx.window.common.CommonFoldingFeature.COMMON_STATE_FLAT;
import static androidx.window.common.CommonFoldingFeature.COMMON_STATE_HALF_OPENED;
+import static androidx.window.util.ExtensionHelper.isZero;
import static androidx.window.util.ExtensionHelper.rotateRectToDisplayRotation;
import static androidx.window.util.ExtensionHelper.transformToWindowSpaceRect;
-import android.annotation.Nullable;
import android.app.Activity;
import android.app.ActivityClient;
import android.app.Application;
import android.app.WindowConfiguration;
+import android.content.ComponentCallbacks;
import android.content.Context;
+import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.IBinder;
import android.util.ArrayMap;
+import android.window.WindowContext;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.annotation.UiContext;
import androidx.window.common.CommonFoldingFeature;
import androidx.window.common.DeviceStateManagerFoldingFeatureProducer;
import androidx.window.common.EmptyLifecycleCallbacksAdapter;
@@ -58,11 +63,14 @@ import java.util.function.Consumer;
public class WindowLayoutComponentImpl implements WindowLayoutComponent {
private static final String TAG = "SampleExtension";
- private final Map<Activity, Consumer<WindowLayoutInfo>> mWindowLayoutChangeListeners =
+ private final Map<Context, Consumer<WindowLayoutInfo>> mWindowLayoutChangeListeners =
new ArrayMap<>();
private final DataProducer<List<CommonFoldingFeature>> mFoldingFeatureProducer;
+ private final Map<IBinder, WindowContextConfigListener> mWindowContextConfigListeners =
+ new ArrayMap<>();
+
public WindowLayoutComponentImpl(@NonNull Context context) {
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new NotifyOnConfigurationChanged());
@@ -78,14 +86,42 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent {
* @param activity hosting a {@link android.view.Window}
* @param consumer interested in receiving updates to {@link WindowLayoutInfo}
*/
+ @Override
public void addWindowLayoutInfoListener(@NonNull Activity activity,
@NonNull Consumer<WindowLayoutInfo> consumer) {
+ addWindowLayoutInfoListener((Context) activity, consumer);
+ }
+
+ /**
+ * Similar to {@link #addWindowLayoutInfoListener(Activity, Consumer)}, but takes a UI Context
+ * as a parameter.
+ */
+ // TODO(b/204073440): Add @Override to hook the API in WM extensions library.
+ public void addWindowLayoutInfoListener(@NonNull @UiContext Context context,
+ @NonNull Consumer<WindowLayoutInfo> consumer) {
+ if (mWindowLayoutChangeListeners.containsKey(context)
+ || mWindowLayoutChangeListeners.containsValue(consumer)) {
+ // Early return if the listener or consumer has been registered.
+ return;
+ }
+ if (!context.isUiContext()) {
+ throw new IllegalArgumentException("Context must be a UI Context, which should be"
+ + " an Activity or a WindowContext");
+ }
mFoldingFeatureProducer.getData((features) -> {
// Get the WindowLayoutInfo from the activity and pass the value to the layoutConsumer.
- WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(activity, features);
+ WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(context, features);
consumer.accept(newWindowLayout);
});
- mWindowLayoutChangeListeners.put(activity, consumer);
+ mWindowLayoutChangeListeners.put(context, consumer);
+
+ if (context instanceof WindowContext) {
+ final IBinder windowContextToken = context.getWindowContextToken();
+ final WindowContextConfigListener listener =
+ new WindowContextConfigListener(windowContextToken);
+ context.registerComponentCallbacks(listener);
+ mWindowContextConfigListeners.put(windowContextToken, listener);
+ }
}
/**
@@ -93,18 +129,30 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent {
*
* @param consumer no longer interested in receiving updates to {@link WindowLayoutInfo}
*/
+ @Override
public void removeWindowLayoutInfoListener(@NonNull Consumer<WindowLayoutInfo> consumer) {
+ for (Context context : mWindowLayoutChangeListeners.keySet()) {
+ if (!mWindowLayoutChangeListeners.get(context).equals(consumer)) {
+ continue;
+ }
+ if (context instanceof WindowContext) {
+ final IBinder token = context.getWindowContextToken();
+ context.unregisterComponentCallbacks(mWindowContextConfigListeners.get(token));
+ mWindowContextConfigListeners.remove(token);
+ }
+ break;
+ }
mWindowLayoutChangeListeners.values().remove(consumer);
}
@NonNull
- Set<Activity> getActivitiesListeningForLayoutChanges() {
+ Set<Context> getContextsListeningForLayoutChanges() {
return mWindowLayoutChangeListeners.keySet();
}
private boolean isListeningForLayoutChanges(IBinder token) {
- for (Activity activity: getActivitiesListeningForLayoutChanges()) {
- if (token.equals(activity.getWindow().getAttributes().token)) {
+ for (Context context: getContextsListeningForLayoutChanges()) {
+ if (token.equals(Context.getToken(context))) {
return true;
}
}
@@ -138,10 +186,10 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent {
}
private void onDisplayFeaturesChanged(List<CommonFoldingFeature> storedFeatures) {
- for (Activity activity : getActivitiesListeningForLayoutChanges()) {
+ for (Context context : getContextsListeningForLayoutChanges()) {
// Get the WindowLayoutInfo from the activity and pass the value to the layoutConsumer.
- Consumer<WindowLayoutInfo> layoutConsumer = mWindowLayoutChangeListeners.get(activity);
- WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(activity, storedFeatures);
+ Consumer<WindowLayoutInfo> layoutConsumer = mWindowLayoutChangeListeners.get(context);
+ WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(context, storedFeatures);
layoutConsumer.accept(newWindowLayout);
}
}
@@ -149,11 +197,12 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent {
/**
* Translates the {@link DisplayFeature} into a {@link WindowLayoutInfo} when a
* valid state is found.
- * @param activity a proxy for the {@link android.view.Window} that contains the
+ * @param context a proxy for the {@link android.view.Window} that contains the
+ * {@link DisplayFeature}.
*/
- private WindowLayoutInfo getWindowLayoutInfo(
- @NonNull Activity activity, List<CommonFoldingFeature> storedFeatures) {
- List<DisplayFeature> displayFeatureList = getDisplayFeatures(activity, storedFeatures);
+ private WindowLayoutInfo getWindowLayoutInfo(@NonNull @UiContext Context context,
+ List<CommonFoldingFeature> storedFeatures) {
+ List<DisplayFeature> displayFeatureList = getDisplayFeatures(context, storedFeatures);
return new WindowLayoutInfo(displayFeatureList);
}
@@ -170,18 +219,18 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent {
* bounds are not valid, constructing a {@link FoldingFeature} will throw an
* {@link IllegalArgumentException} since this can cause negative UI effects down stream.
*
- * @param activity a proxy for the {@link android.view.Window} that contains the
+ * @param context a proxy for the {@link android.view.Window} that contains the
* {@link DisplayFeature}.
* are within the {@link android.view.Window} of the {@link Activity}
*/
private List<DisplayFeature> getDisplayFeatures(
- @NonNull Activity activity, List<CommonFoldingFeature> storedFeatures) {
+ @NonNull @UiContext Context context, List<CommonFoldingFeature> storedFeatures) {
List<DisplayFeature> features = new ArrayList<>();
- if (!shouldReportDisplayFeatures(activity)) {
+ if (!shouldReportDisplayFeatures(context)) {
return features;
}
- int displayId = activity.getDisplay().getDisplayId();
+ int displayId = context.getDisplay().getDisplayId();
for (CommonFoldingFeature baseFeature : storedFeatures) {
Integer state = convertToExtensionState(baseFeature.getState());
if (state == null) {
@@ -189,9 +238,9 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent {
}
Rect featureRect = baseFeature.getRect();
rotateRectToDisplayRotation(displayId, featureRect);
- transformToWindowSpaceRect(activity, featureRect);
+ transformToWindowSpaceRect(context, featureRect);
- if (!isRectZero(featureRect)) {
+ if (!isZero(featureRect)) {
// TODO(b/228641877): Remove guarding when fixed.
features.add(new FoldingFeature(featureRect, baseFeature.getType(), state));
}
@@ -203,15 +252,21 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent {
* Checks whether display features should be reported for the activity.
* TODO(b/238948678): Support reporting display features in all windowing modes.
*/
- private boolean shouldReportDisplayFeatures(@NonNull Activity activity) {
- int displayId = activity.getDisplay().getDisplayId();
+ private boolean shouldReportDisplayFeatures(@NonNull @UiContext Context context) {
+ int displayId = context.getDisplay().getDisplayId();
if (displayId != DEFAULT_DISPLAY) {
// Display features are not supported on secondary displays.
return false;
}
- final int taskWindowingMode = ActivityClient.getInstance().getTaskWindowingMode(
- activity.getActivityToken());
- if (taskWindowingMode == -1) {
+ final int windowingMode;
+ if (context instanceof Activity) {
+ windowingMode = ActivityClient.getInstance().getTaskWindowingMode(
+ context.getActivityToken());
+ } else {
+ windowingMode = context.getResources().getConfiguration().windowConfiguration
+ .getWindowingMode();
+ }
+ if (windowingMode == -1) {
// If we cannot determine the task windowing mode for any reason, it is likely that we
// won't be able to determine its position correctly as well. DisplayFeatures' bounds
// in this case can't be computed correctly, so we should skip.
@@ -219,36 +274,43 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent {
}
// It is recommended not to report any display features in multi-window mode, since it
// won't be possible to synchronize the display feature positions with window movement.
- return !WindowConfiguration.inMultiWindowMode(taskWindowingMode);
+ return !WindowConfiguration.inMultiWindowMode(windowingMode);
}
- /**
- * Returns {@link true} if a {@link Rect} has zero width and zero height,
- * {@code false} otherwise.
- */
- private boolean isRectZero(Rect rect) {
- return rect.width() == 0 && rect.height() == 0;
+ private void onDisplayFeaturesChangedIfListening(@NonNull IBinder token) {
+ if (isListeningForLayoutChanges(token)) {
+ mFoldingFeatureProducer.getData(
+ WindowLayoutComponentImpl.this::onDisplayFeaturesChanged);
+ }
}
private final class NotifyOnConfigurationChanged extends EmptyLifecycleCallbacksAdapter {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
super.onActivityCreated(activity, savedInstanceState);
- onDisplayFeaturesChangedIfListening(activity);
+ onDisplayFeaturesChangedIfListening(activity.getActivityToken());
}
@Override
public void onActivityConfigurationChanged(Activity activity) {
super.onActivityConfigurationChanged(activity);
- onDisplayFeaturesChangedIfListening(activity);
+ onDisplayFeaturesChangedIfListening(activity.getActivityToken());
+ }
+ }
+
+ private final class WindowContextConfigListener implements ComponentCallbacks {
+ final IBinder mToken;
+
+ WindowContextConfigListener(IBinder token) {
+ mToken = token;
}
- private void onDisplayFeaturesChangedIfListening(Activity activity) {
- IBinder token = activity.getWindow().getAttributes().token;
- if (token == null || isListeningForLayoutChanges(token)) {
- mFoldingFeatureProducer.getData(
- WindowLayoutComponentImpl.this::onDisplayFeaturesChanged);
- }
+ @Override
+ public void onConfigurationChanged(@NonNull Configuration newConfig) {
+ onDisplayFeaturesChangedIfListening(mToken);
}
+
+ @Override
+ public void onLowMemory() {}
}
}
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/util/BaseDataProducer.java b/libs/WindowManager/Jetpack/src/androidx/window/util/BaseDataProducer.java
index 0da44ac36a6e..cbaa27712015 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/util/BaseDataProducer.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/util/BaseDataProducer.java
@@ -16,6 +16,7 @@
package androidx.window.util;
+import androidx.annotation.GuardedBy;
import androidx.annotation.NonNull;
import java.util.LinkedHashSet;
@@ -25,25 +26,45 @@ import java.util.function.Consumer;
/**
* Base class that provides the implementation for the callback mechanism of the
- * {@link DataProducer} API.
+ * {@link DataProducer} API. This class is thread safe for adding, removing, and notifying
+ * consumers.
*
* @param <T> The type of data this producer returns through {@link DataProducer#getData}.
*/
public abstract class BaseDataProducer<T> implements DataProducer<T> {
+
+ private final Object mLock = new Object();
+ @GuardedBy("mLock")
private final Set<Consumer<T>> mCallbacks = new LinkedHashSet<>();
+ /**
+ * Adds a callback to the set of callbacks listening for data. Data is delivered through
+ * {@link BaseDataProducer#notifyDataChanged(Object)}. This method is thread safe. Callers
+ * should ensure that callbacks are thread safe.
+ * @param callback that will receive data from the producer.
+ */
@Override
public final void addDataChangedCallback(@NonNull Consumer<T> callback) {
- mCallbacks.add(callback);
- Optional<T> currentData = getCurrentData();
- currentData.ifPresent(callback);
- onListenersChanged(mCallbacks);
+ synchronized (mLock) {
+ mCallbacks.add(callback);
+ Optional<T> currentData = getCurrentData();
+ currentData.ifPresent(callback);
+ onListenersChanged(mCallbacks);
+ }
}
+ /**
+ * Removes a callback to the set of callbacks listening for data. This method is thread safe
+ * for adding.
+ * @param callback that was registered in
+ * {@link BaseDataProducer#addDataChangedCallback(Consumer)}.
+ */
@Override
public final void removeDataChangedCallback(@NonNull Consumer<T> callback) {
- mCallbacks.remove(callback);
- onListenersChanged(mCallbacks);
+ synchronized (mLock) {
+ mCallbacks.remove(callback);
+ onListenersChanged(mCallbacks);
+ }
}
protected void onListenersChanged(Set<Consumer<T>> callbacks) {}
@@ -56,11 +77,14 @@ public abstract class BaseDataProducer<T> implements DataProducer<T> {
/**
* Called to notify all registered consumers that the data provided
- * by {@link DataProducer#getData} has changed.
+ * by {@link DataProducer#getData} has changed. Calls to this are thread save but callbacks need
+ * to ensure thread safety.
*/
protected void notifyDataChanged(T value) {
- for (Consumer<T> callback : mCallbacks) {
- callback.accept(value);
+ synchronized (mLock) {
+ for (Consumer<T> callback : mCallbacks) {
+ callback.accept(value);
+ }
}
}
} \ No newline at end of file
diff --git a/libs/WindowManager/Jetpack/src/androidx/window/util/ExtensionHelper.java b/libs/WindowManager/Jetpack/src/androidx/window/util/ExtensionHelper.java
index 2a593f15a9de..31bf96313a95 100644
--- a/libs/WindowManager/Jetpack/src/androidx/window/util/ExtensionHelper.java
+++ b/libs/WindowManager/Jetpack/src/androidx/window/util/ExtensionHelper.java
@@ -21,14 +21,15 @@ import static android.view.Surface.ROTATION_180;
import static android.view.Surface.ROTATION_270;
import static android.view.Surface.ROTATION_90;
-import android.app.Activity;
+import android.content.Context;
import android.graphics.Rect;
import android.hardware.display.DisplayManagerGlobal;
import android.view.DisplayInfo;
import android.view.Surface;
+import android.view.WindowManager;
import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
+import androidx.annotation.UiContext;
/**
* Util class for both Sidecar and Extensions.
@@ -86,12 +87,9 @@ public final class ExtensionHelper {
}
/** Transforms rectangle from absolute coordinate space to the window coordinate space. */
- public static void transformToWindowSpaceRect(Activity activity, Rect inOutRect) {
- Rect windowRect = getWindowBounds(activity);
- if (windowRect == null) {
- inOutRect.setEmpty();
- return;
- }
+ public static void transformToWindowSpaceRect(@NonNull @UiContext Context context,
+ Rect inOutRect) {
+ Rect windowRect = getWindowBounds(context);
if (!Rect.intersects(inOutRect, windowRect)) {
inOutRect.setEmpty();
return;
@@ -103,9 +101,9 @@ public final class ExtensionHelper {
/**
* Gets the current window bounds in absolute coordinates.
*/
- @Nullable
- private static Rect getWindowBounds(@NonNull Activity activity) {
- return activity.getWindowManager().getCurrentWindowMetrics().getBounds();
+ @NonNull
+ private static Rect getWindowBounds(@NonNull @UiContext Context context) {
+ return context.getSystemService(WindowManager.class).getCurrentWindowMetrics().getBounds();
}
/**
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
index 5bf88b119661..aeaf6eda9809 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java
@@ -111,6 +111,9 @@ public class BubbleStackView extends FrameLayout
public static final boolean HOME_GESTURE_ENABLED =
SystemProperties.getBoolean("persist.wm.debug.bubbles_home_gesture", true);
+ public static final boolean ENABLE_FLING_TO_DISMISS_BUBBLE =
+ SystemProperties.getBoolean("persist.wm.debug.fling_to_dismiss_bubble", true);
+
private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleStackView" : TAG_BUBBLES;
/** How far the flyout needs to be dragged before it's dismissed regardless of velocity. */
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java
index ae434bcec6c4..b91062f891e8 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java
@@ -19,6 +19,7 @@ package com.android.wm.shell.bubbles.animation;
import static android.view.View.LAYOUT_DIRECTION_RTL;
import static com.android.wm.shell.bubbles.BubblePositioner.NUM_VISIBLE_WHEN_RESTING;
+import static com.android.wm.shell.bubbles.BubbleStackView.ENABLE_FLING_TO_DISMISS_BUBBLE;
import static com.android.wm.shell.bubbles.BubbleStackView.HOME_GESTURE_ENABLED;
import android.content.res.Resources;
@@ -366,6 +367,7 @@ public class ExpandedAnimationController
mMagnetizedBubbleDraggingOut.setMagnetListener(listener);
mMagnetizedBubbleDraggingOut.setHapticsEnabled(true);
mMagnetizedBubbleDraggingOut.setFlingToTargetMinVelocity(FLING_TO_DISMISS_MIN_VELOCITY);
+ mMagnetizedBubbleDraggingOut.setFlingToTargetEnabled(ENABLE_FLING_TO_DISMISS_BUBBLE);
}
private void springBubbleTo(View bubble, float x, float y) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java
index 4e2cbfd82fcc..961722ba9bc0 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java
@@ -17,6 +17,7 @@
package com.android.wm.shell.bubbles.animation;
import static com.android.wm.shell.bubbles.BubblePositioner.NUM_VISIBLE_WHEN_RESTING;
+import static com.android.wm.shell.bubbles.BubbleStackView.ENABLE_FLING_TO_DISMISS_BUBBLE;
import android.content.ContentResolver;
import android.content.res.Resources;
@@ -1028,6 +1029,7 @@ public class StackAnimationController extends
};
mMagnetizedStack.setHapticsEnabled(true);
mMagnetizedStack.setFlingToTargetMinVelocity(FLING_TO_DISMISS_MIN_VELOCITY);
+ mMagnetizedStack.setFlingToTargetEnabled(ENABLE_FLING_TO_DISMISS_BUBBLE);
}
final ContentResolver contentResolver = mLayout.getContext().getContentResolver();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
index ceaa64ef8290..7a736ccab5d1 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
@@ -85,6 +85,7 @@ import com.android.wm.shell.transition.Transitions;
import com.android.wm.shell.unfold.ShellUnfoldProgressProvider;
import com.android.wm.shell.unfold.UnfoldAnimationController;
import com.android.wm.shell.unfold.UnfoldTransitionHandler;
+import com.android.wm.shell.windowdecor.WindowDecorViewModel;
import java.util.Optional;
@@ -294,25 +295,33 @@ public abstract class WMShellBaseModule {
// Workaround for dynamic overriding with a default implementation, see {@link DynamicOverride}
@BindsOptionalOf
@DynamicOverride
- abstract FullscreenTaskListener optionalFullscreenTaskListener();
+ abstract FullscreenTaskListener<?> optionalFullscreenTaskListener();
@WMSingleton
@Provides
- static FullscreenTaskListener provideFullscreenTaskListener(
- @DynamicOverride Optional<FullscreenTaskListener> fullscreenTaskListener,
+ static FullscreenTaskListener<?> provideFullscreenTaskListener(
+ @DynamicOverride Optional<FullscreenTaskListener<?>> fullscreenTaskListener,
ShellInit shellInit,
ShellTaskOrganizer shellTaskOrganizer,
SyncTransactionQueue syncQueue,
- Optional<RecentTasksController> recentTasksOptional) {
+ Optional<RecentTasksController> recentTasksOptional,
+ Optional<WindowDecorViewModel<?>> windowDecorViewModelOptional) {
if (fullscreenTaskListener.isPresent()) {
return fullscreenTaskListener.get();
} else {
return new FullscreenTaskListener(shellInit, shellTaskOrganizer, syncQueue,
- recentTasksOptional);
+ recentTasksOptional, windowDecorViewModelOptional);
}
}
//
+ // Window Decoration
+ //
+
+ @BindsOptionalOf
+ abstract WindowDecorViewModel<?> optionalWindowDecorViewModel();
+
+ //
// Unfold transition
//
@@ -680,7 +689,7 @@ public abstract class WMShellBaseModule {
Optional<SplitScreenController> splitScreenOptional,
Optional<Pip> pipOptional,
Optional<PipTouchHandler> pipTouchHandlerOptional,
- FullscreenTaskListener fullscreenTaskListener,
+ FullscreenTaskListener<?> fullscreenTaskListener,
Optional<UnfoldAnimationController> unfoldAnimationController,
Optional<UnfoldTransitionHandler> unfoldTransitionHandler,
Optional<FreeformComponents> freeformComponents,
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 4fe32556a94d..c64d1134a4ab 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
@@ -55,6 +55,7 @@ import com.android.wm.shell.draganddrop.DragAndDropController;
import com.android.wm.shell.freeform.FreeformComponents;
import com.android.wm.shell.freeform.FreeformTaskListener;
import com.android.wm.shell.freeform.FreeformTaskTransitionHandler;
+import com.android.wm.shell.fullscreen.FullscreenTaskListener;
import com.android.wm.shell.onehanded.OneHandedController;
import com.android.wm.shell.pip.Pip;
import com.android.wm.shell.pip.PipAnimationController;
@@ -233,6 +234,7 @@ public abstract class WMShellModule {
ShellInit shellInit,
Transitions transitions,
WindowDecorViewModel<?> windowDecorViewModel,
+ FullscreenTaskListener<?> fullscreenTaskListener,
FreeformTaskListener<?> freeformTaskListener) {
// TODO(b/238217847): Temporarily add this check here until we can remove the dynamic
// override for this controller from the base module
@@ -240,7 +242,7 @@ public abstract class WMShellModule {
? shellInit
: null;
return new FreeformTaskTransitionHandler(init, transitions,
- windowDecorViewModel, freeformTaskListener);
+ windowDecorViewModel, fullscreenTaskListener, freeformTaskListener);
}
//
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskListener.java b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskListener.java
index ab66107399c6..8dcdda1895e6 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskListener.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskListener.java
@@ -187,12 +187,14 @@ public class FreeformTaskListener<T extends AutoCloseable>
RunningTaskInfo taskInfo,
SurfaceControl.Transaction startT,
SurfaceControl.Transaction finishT) {
- T windowDecor = mWindowDecorOfVanishedTasks.get(taskInfo.taskId);
- mWindowDecorOfVanishedTasks.remove(taskInfo.taskId);
+ T windowDecor;
final State<T> state = mTasks.get(taskInfo.taskId);
if (state != null) {
- windowDecor = windowDecor == null ? state.mWindowDecoration : windowDecor;
+ windowDecor = state.mWindowDecoration;
state.mWindowDecoration = null;
+ } else {
+ windowDecor =
+ mWindowDecorOfVanishedTasks.removeReturnOld(taskInfo.taskId);
}
mWindowDecorationViewModel.setupWindowDecorationForTransition(
taskInfo, startT, finishT, windowDecor);
@@ -231,7 +233,8 @@ public class FreeformTaskListener<T extends AutoCloseable>
if (mWindowDecorOfVanishedTasks.size() == 0) {
return;
}
- Log.w(TAG, "Clearing window decors of vanished tasks. There could be visual defects "
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
+ "Clearing window decors of vanished tasks. There could be visual defects "
+ "if any of them is used later in transitions.");
for (int i = 0; i < mWindowDecorOfVanishedTasks.size(); ++i) {
releaseWindowDecor(mWindowDecorOfVanishedTasks.valueAt(i));
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java
index a1e9f938d280..30f625e24118 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java
@@ -32,6 +32,7 @@ import android.window.WindowContainerTransaction;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import com.android.wm.shell.fullscreen.FullscreenTaskListener;
import com.android.wm.shell.sysui.ShellInit;
import com.android.wm.shell.transition.Transitions;
import com.android.wm.shell.windowdecor.WindowDecorViewModel;
@@ -50,6 +51,7 @@ public class FreeformTaskTransitionHandler
private final Transitions mTransitions;
private final FreeformTaskListener<?> mFreeformTaskListener;
+ private final FullscreenTaskListener<?> mFullscreenTaskListener;
private final WindowDecorViewModel<?> mWindowDecorViewModel;
private final List<IBinder> mPendingTransitionTokens = new ArrayList<>();
@@ -58,8 +60,10 @@ public class FreeformTaskTransitionHandler
ShellInit shellInit,
Transitions transitions,
WindowDecorViewModel<?> windowDecorViewModel,
+ FullscreenTaskListener<?> fullscreenTaskListener,
FreeformTaskListener<?> freeformTaskListener) {
mTransitions = transitions;
+ mFullscreenTaskListener = fullscreenTaskListener;
mFreeformTaskListener = freeformTaskListener;
mWindowDecorViewModel = windowDecorViewModel;
if (shellInit != null && Transitions.ENABLE_SHELL_TRANSITIONS) {
@@ -150,10 +154,16 @@ public class FreeformTaskTransitionHandler
TransitionInfo.Change change,
SurfaceControl.Transaction startT,
SurfaceControl.Transaction finishT) {
- if (change.getTaskInfo().getWindowingMode() != WINDOWING_MODE_FREEFORM) {
- return false;
+ switch (change.getTaskInfo().getWindowingMode()){
+ case WINDOWING_MODE_FREEFORM:
+ mFreeformTaskListener.createWindowDecoration(change, startT, finishT);
+ break;
+ case WINDOWING_MODE_FULLSCREEN:
+ mFullscreenTaskListener.createWindowDecoration(change, startT, finishT);
+ break;
+ default:
+ return false;
}
- mFreeformTaskListener.createWindowDecoration(change, startT, finishT);
// Intercepted transition to manage the window decorations. Let other handlers animate.
return false;
@@ -164,15 +174,22 @@ public class FreeformTaskTransitionHandler
ArrayList<AutoCloseable> windowDecors,
SurfaceControl.Transaction startT,
SurfaceControl.Transaction finishT) {
- if (change.getTaskInfo().getWindowingMode() != WINDOWING_MODE_FREEFORM) {
- return false;
+ final AutoCloseable windowDecor;
+ switch (change.getTaskInfo().getWindowingMode()) {
+ case WINDOWING_MODE_FREEFORM:
+ windowDecor = mFreeformTaskListener.giveWindowDecoration(change.getTaskInfo(),
+ startT, finishT);
+ break;
+ case WINDOWING_MODE_FULLSCREEN:
+ windowDecor = mFullscreenTaskListener.giveWindowDecoration(change.getTaskInfo(),
+ startT, finishT);
+ break;
+ default:
+ windowDecor = null;
}
- final AutoCloseable windowDecor =
- mFreeformTaskListener.giveWindowDecoration(change.getTaskInfo(), startT, finishT);
if (windowDecor != null) {
windowDecors.add(windowDecor);
}
-
// Intercepted transition to manage the window decorations. Let other handlers animate.
return false;
}
@@ -197,24 +214,29 @@ public class FreeformTaskTransitionHandler
}
boolean handled = false;
+ boolean adopted = false;
final ActivityManager.RunningTaskInfo taskInfo = change.getTaskInfo();
if (type == Transitions.TRANSIT_MAXIMIZE
&& taskInfo.getWindowingMode() == WINDOWING_MODE_FULLSCREEN) {
handled = true;
windowDecor = mFreeformTaskListener.giveWindowDecoration(
change.getTaskInfo(), startT, finishT);
- // TODO(b/235638450): Let fullscreen task listener adopt the window decor.
+ adopted = mFullscreenTaskListener.adoptWindowDecoration(change,
+ startT, finishT, windowDecor);
}
if (type == Transitions.TRANSIT_RESTORE_FROM_MAXIMIZE
&& taskInfo.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
handled = true;
- // TODO(b/235638450): Let fullscreen task listener transfer the window decor.
- mFreeformTaskListener.adoptWindowDecoration(change, startT, finishT, windowDecor);
+ windowDecor = mFullscreenTaskListener.giveWindowDecoration(
+ change.getTaskInfo(), startT, finishT);
+ adopted = mFreeformTaskListener.adoptWindowDecoration(change,
+ startT, finishT, windowDecor);
}
- releaseWindowDecor(windowDecor);
-
+ if (!adopted) {
+ releaseWindowDecor(windowDecor);
+ }
return handled;
}
@@ -225,7 +247,7 @@ public class FreeformTaskTransitionHandler
releaseWindowDecor(windowDecor);
}
mFreeformTaskListener.onTaskTransitionFinished();
- // TODO(b/235638450): Dispatch it to fullscreen task listener.
+ mFullscreenTaskListener.onTaskTransitionFinished();
finishCallback.onTransitionFinished(null, null);
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/fullscreen/FullscreenTaskListener.java b/libs/WindowManager/Shell/src/com/android/wm/shell/fullscreen/FullscreenTaskListener.java
index 0ba4afc24c45..0d75bc451b72 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/fullscreen/FullscreenTaskListener.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/fullscreen/FullscreenTaskListener.java
@@ -16,16 +16,21 @@
package com.android.wm.shell.fullscreen;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
+
import static com.android.wm.shell.ShellTaskOrganizer.TASK_LISTENER_TYPE_FULLSCREEN;
import static com.android.wm.shell.ShellTaskOrganizer.taskListenerTypeToString;
+import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.graphics.Point;
-import android.util.Slog;
+import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceControl;
+import android.window.TransitionInfo;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import com.android.internal.protolog.common.ProtoLog;
import com.android.wm.shell.ShellTaskOrganizer;
@@ -34,36 +39,49 @@ import com.android.wm.shell.protolog.ShellProtoLogGroup;
import com.android.wm.shell.recents.RecentTasksController;
import com.android.wm.shell.sysui.ShellInit;
import com.android.wm.shell.transition.Transitions;
+import com.android.wm.shell.windowdecor.WindowDecorViewModel;
import java.io.PrintWriter;
import java.util.Optional;
/**
* Organizes tasks presented in {@link android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN}.
+ * @param <T> the type of window decoration instance
*/
-public class FullscreenTaskListener implements ShellTaskOrganizer.TaskListener {
+public class FullscreenTaskListener<T extends AutoCloseable>
+ implements ShellTaskOrganizer.TaskListener {
private static final String TAG = "FullscreenTaskListener";
private final ShellTaskOrganizer mShellTaskOrganizer;
- private final SyncTransactionQueue mSyncQueue;
- private final Optional<RecentTasksController> mRecentTasksOptional;
- private final SparseArray<TaskData> mDataByTaskId = new SparseArray<>();
+ private final SparseArray<State<T>> mTasks = new SparseArray<>();
+ private final SparseArray<T> mWindowDecorOfVanishedTasks = new SparseArray<>();
+ private static class State<T extends AutoCloseable> {
+ RunningTaskInfo mTaskInfo;
+ SurfaceControl mLeash;
+ T mWindowDecoration;
+ }
+ private final SyncTransactionQueue mSyncQueue;
+ private final Optional<RecentTasksController> mRecentTasksOptional;
+ private final Optional<WindowDecorViewModel<T>> mWindowDecorViewModelOptional;
/**
* This constructor is used by downstream products.
*/
public FullscreenTaskListener(SyncTransactionQueue syncQueue) {
- this(null /* shellInit */, null /* shellTaskOrganizer */, syncQueue, Optional.empty());
+ this(null /* shellInit */, null /* shellTaskOrganizer */, syncQueue, Optional.empty(),
+ Optional.empty());
}
public FullscreenTaskListener(ShellInit shellInit,
ShellTaskOrganizer shellTaskOrganizer,
SyncTransactionQueue syncQueue,
- Optional<RecentTasksController> recentTasksOptional) {
+ Optional<RecentTasksController> recentTasksOptional,
+ Optional<WindowDecorViewModel<T>> windowDecorViewModelOptional) {
mShellTaskOrganizer = shellTaskOrganizer;
mSyncQueue = syncQueue;
mRecentTasksOptional = recentTasksOptional;
+ mWindowDecorViewModelOptional = windowDecorViewModelOptional;
// Note: Some derivative FullscreenTaskListener implementations do not use ShellInit
if (shellInit != null) {
shellInit.addInitCallback(this::onInit, this);
@@ -76,55 +94,204 @@ public class FullscreenTaskListener implements ShellTaskOrganizer.TaskListener {
@Override
public void onTaskAppeared(RunningTaskInfo taskInfo, SurfaceControl leash) {
- if (mDataByTaskId.get(taskInfo.taskId) != null) {
+ if (mTasks.get(taskInfo.taskId) != null) {
throw new IllegalStateException("Task appeared more than once: #" + taskInfo.taskId);
}
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TASK_ORG, "Fullscreen Task Appeared: #%d",
taskInfo.taskId);
final Point positionInParent = taskInfo.positionInParent;
- mDataByTaskId.put(taskInfo.taskId, new TaskData(leash, positionInParent));
-
- if (Transitions.ENABLE_SHELL_TRANSITIONS) return;
- mSyncQueue.runInSync(t -> {
- // Reset several properties back to fullscreen (PiP, for example, leaves all these
- // properties in a bad state).
- t.setWindowCrop(leash, null);
- t.setPosition(leash, positionInParent.x, positionInParent.y);
- t.setAlpha(leash, 1f);
- t.setMatrix(leash, 1, 0, 0, 1);
- t.show(leash);
- });
+ final State<T> state = new State();
+ state.mLeash = leash;
+ state.mTaskInfo = taskInfo;
+ mTasks.put(taskInfo.taskId, state);
updateRecentsForVisibleFullscreenTask(taskInfo);
+ if (Transitions.ENABLE_SHELL_TRANSITIONS) return;
+ if (shouldShowWindowDecor(taskInfo) && mWindowDecorViewModelOptional.isPresent()) {
+ SurfaceControl.Transaction t = new SurfaceControl.Transaction();
+ state.mWindowDecoration =
+ mWindowDecorViewModelOptional.get().createWindowDecoration(taskInfo,
+ leash, t, t);
+ t.apply();
+ } else {
+ mSyncQueue.runInSync(t -> {
+ // Reset several properties back to fullscreen (PiP, for example, leaves all these
+ // properties in a bad state).
+ t.setWindowCrop(leash, null);
+ t.setPosition(leash, positionInParent.x, positionInParent.y);
+ t.setAlpha(leash, 1f);
+ t.setMatrix(leash, 1, 0, 0, 1);
+ t.show(leash);
+ });
+ }
}
@Override
public void onTaskInfoChanged(RunningTaskInfo taskInfo) {
- if (Transitions.ENABLE_SHELL_TRANSITIONS) return;
-
+ final State<T> state = mTasks.get(taskInfo.taskId);
+ final Point oldPositionInParent = state.mTaskInfo.positionInParent;
+ state.mTaskInfo = taskInfo;
+ if (state.mWindowDecoration != null) {
+ mWindowDecorViewModelOptional.get().onTaskInfoChanged(
+ state.mTaskInfo, state.mWindowDecoration);
+ }
updateRecentsForVisibleFullscreenTask(taskInfo);
+ if (Transitions.ENABLE_SHELL_TRANSITIONS) return;
- final TaskData data = mDataByTaskId.get(taskInfo.taskId);
- final Point positionInParent = taskInfo.positionInParent;
- if (!positionInParent.equals(data.positionInParent)) {
- data.positionInParent.set(positionInParent.x, positionInParent.y);
+ final Point positionInParent = state.mTaskInfo.positionInParent;
+ if (!oldPositionInParent.equals(state.mTaskInfo.positionInParent)) {
mSyncQueue.runInSync(t -> {
- t.setPosition(data.surface, positionInParent.x, positionInParent.y);
+ t.setPosition(state.mLeash, positionInParent.x, positionInParent.y);
});
}
}
@Override
- public void onTaskVanished(RunningTaskInfo taskInfo) {
- if (mDataByTaskId.get(taskInfo.taskId) == null) {
- Slog.e(TAG, "Task already vanished: #" + taskInfo.taskId);
+ public void onTaskVanished(ActivityManager.RunningTaskInfo taskInfo) {
+ final State<T> state = mTasks.get(taskInfo.taskId);
+ if (state == null) {
+ // This is possible if the transition happens before this method.
return;
}
-
- mDataByTaskId.remove(taskInfo.taskId);
-
ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TASK_ORG, "Fullscreen Task Vanished: #%d",
taskInfo.taskId);
+ mTasks.remove(taskInfo.taskId);
+
+ if (Transitions.ENABLE_SHELL_TRANSITIONS) {
+ // Save window decorations of closing tasks so that we can hand them over to the
+ // transition system if this method happens before the transition. In case where the
+ // transition didn't happen, it'd be cleared when the next transition finished.
+ if (state.mWindowDecoration != null) {
+ mWindowDecorOfVanishedTasks.put(taskInfo.taskId, state.mWindowDecoration);
+ }
+ return;
+ }
+ releaseWindowDecor(state.mWindowDecoration);
+ }
+
+ /**
+ * Creates a window decoration for a transition.
+ *
+ * @param change the change of this task transition that needs to have the task layer as the
+ * leash
+ */
+ public void createWindowDecoration(TransitionInfo.Change change,
+ SurfaceControl.Transaction startT, SurfaceControl.Transaction finishT) {
+ final State<T> state = createOrUpdateTaskState(change.getTaskInfo(), change.getLeash());
+ if (!mWindowDecorViewModelOptional.isPresent()
+ || !shouldShowWindowDecor(state.mTaskInfo)) {
+ return;
+ }
+
+ state.mWindowDecoration = mWindowDecorViewModelOptional.get().createWindowDecoration(
+ state.mTaskInfo, state.mLeash, startT, finishT);
+ }
+
+ /**
+ * Adopt the incoming window decoration and lets the window decoration prepare for a transition.
+ *
+ * @param change the change of this task transition that needs to have the task layer as the
+ * leash
+ * @param startT the start transaction of this transition
+ * @param finishT the finish transaction of this transition
+ * @param windowDecor the window decoration to adopt
+ * @return {@code true} if it adopts the window decoration; {@code false} otherwise
+ */
+ public boolean adoptWindowDecoration(
+ TransitionInfo.Change change,
+ SurfaceControl.Transaction startT,
+ SurfaceControl.Transaction finishT,
+ @Nullable AutoCloseable windowDecor) {
+ if (!mWindowDecorViewModelOptional.isPresent()
+ || !shouldShowWindowDecor(change.getTaskInfo())) {
+ return false;
+ }
+ final State<T> state = createOrUpdateTaskState(change.getTaskInfo(), change.getLeash());
+ state.mWindowDecoration = mWindowDecorViewModelOptional.get().adoptWindowDecoration(
+ windowDecor);
+ if (state.mWindowDecoration != null) {
+ mWindowDecorViewModelOptional.get().setupWindowDecorationForTransition(
+ state.mTaskInfo, startT, finishT, state.mWindowDecoration);
+ return true;
+ } else {
+ state.mWindowDecoration = mWindowDecorViewModelOptional.get().createWindowDecoration(
+ state.mTaskInfo, state.mLeash, startT, finishT);
+ return false;
+ }
+ }
+
+ /**
+ * Clear window decors of vanished tasks.
+ */
+ public void onTaskTransitionFinished() {
+ if (mWindowDecorOfVanishedTasks.size() == 0) {
+ return;
+ }
+ ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS,
+ "Clearing window decors of vanished tasks. There could be visual defects "
+ + "if any of them is used later in transitions.");
+ for (int i = 0; i < mWindowDecorOfVanishedTasks.size(); ++i) {
+ releaseWindowDecor(mWindowDecorOfVanishedTasks.valueAt(i));
+ }
+ mWindowDecorOfVanishedTasks.clear();
+ }
+
+ /**
+ * Gives out the ownership of the task's window decoration. The given task is leaving (of has
+ * left) this task listener. This is the transition system asking for the ownership.
+ *
+ * @param taskInfo the maximizing task
+ * @return the window decor of the maximizing task if any
+ */
+ public T giveWindowDecoration(
+ ActivityManager.RunningTaskInfo taskInfo,
+ SurfaceControl.Transaction startT,
+ SurfaceControl.Transaction finishT) {
+ T windowDecor;
+ final State<T> state = mTasks.get(taskInfo.taskId);
+ if (state != null) {
+ windowDecor = state.mWindowDecoration;
+ state.mWindowDecoration = null;
+ } else {
+ windowDecor =
+ mWindowDecorOfVanishedTasks.removeReturnOld(taskInfo.taskId);
+ }
+ if (mWindowDecorViewModelOptional.isPresent()) {
+ mWindowDecorViewModelOptional.get().setupWindowDecorationForTransition(
+ taskInfo, startT, finishT, windowDecor);
+ }
+
+ return windowDecor;
+ }
+
+ private State<T> createOrUpdateTaskState(ActivityManager.RunningTaskInfo taskInfo,
+ SurfaceControl leash) {
+ State<T> state = mTasks.get(taskInfo.taskId);
+ if (state != null) {
+ updateTaskInfo(taskInfo);
+ return state;
+ }
+
+ state = new State<T>();
+ state.mTaskInfo = taskInfo;
+ state.mLeash = leash;
+ mTasks.put(taskInfo.taskId, state);
+
+ return state;
+ }
+
+ private State<T> updateTaskInfo(ActivityManager.RunningTaskInfo taskInfo) {
+ final State<T> state = mTasks.get(taskInfo.taskId);
+ state.mTaskInfo = taskInfo;
+ return state;
+ }
+
+ private void releaseWindowDecor(T windowDecor) {
+ try {
+ windowDecor.close();
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to release window decoration.", e);
+ }
}
private void updateRecentsForVisibleFullscreenTask(RunningTaskInfo taskInfo) {
@@ -148,17 +315,17 @@ public class FullscreenTaskListener implements ShellTaskOrganizer.TaskListener {
}
private SurfaceControl findTaskSurface(int taskId) {
- if (!mDataByTaskId.contains(taskId)) {
+ if (!mTasks.contains(taskId)) {
throw new IllegalArgumentException("There is no surface for taskId=" + taskId);
}
- return mDataByTaskId.get(taskId).surface;
+ return mTasks.get(taskId).mLeash;
}
@Override
public void dump(@NonNull PrintWriter pw, String prefix) {
final String innerPrefix = prefix + " ";
pw.println(prefix + this);
- pw.println(innerPrefix + mDataByTaskId.size() + " Tasks");
+ pw.println(innerPrefix + mTasks.size() + " Tasks");
}
@Override
@@ -166,16 +333,10 @@ public class FullscreenTaskListener implements ShellTaskOrganizer.TaskListener {
return TAG + ":" + taskListenerTypeToString(TASK_LISTENER_TYPE_FULLSCREEN);
}
- /**
- * Per-task data for each managed task.
- */
- private static class TaskData {
- public final SurfaceControl surface;
- public final Point positionInParent;
-
- public TaskData(SurfaceControl surface, Point positionInParent) {
- this.surface = surface;
- this.positionInParent = positionInParent;
- }
+ private static boolean shouldShowWindowDecor(RunningTaskInfo taskInfo) {
+ return taskInfo.getConfiguration().windowConfiguration.getDisplayWindowingMode()
+ == WINDOWING_MODE_FREEFORM;
}
+
+
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java
index 44d22029a5e9..afb64c9eec41 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java
@@ -33,6 +33,7 @@ import android.content.Context;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Debug;
+import android.os.SystemProperties;
import com.android.internal.protolog.common.ProtoLog;
import com.android.wm.shell.R;
@@ -58,6 +59,8 @@ import kotlin.jvm.functions.Function0;
public class PipMotionHelper implements PipAppOpsListener.Callback,
FloatingContentCoordinator.FloatingContent {
+ public static final boolean ENABLE_FLING_TO_DISMISS_PIP =
+ SystemProperties.getBoolean("persist.wm.debug.fling_to_dismiss_pip", true);
private static final String TAG = "PipMotionHelper";
private static final boolean DEBUG = false;
@@ -704,6 +707,7 @@ public class PipMotionHelper implements PipAppOpsListener.Callback,
loc[1] = animatedPipBounds.top;
}
};
+ mMagnetizedPip.setFlingToTargetEnabled(ENABLE_FLING_TO_DISMISS_PIP);
}
return mMagnetizedPip;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
index 6c659667a4a7..cff60f5e5b6c 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
@@ -44,6 +44,8 @@ import static android.view.WindowManager.TRANSIT_RELAUNCH;
import static android.view.WindowManager.TRANSIT_TO_BACK;
import static android.view.WindowManager.TRANSIT_TO_FRONT;
import static android.view.WindowManager.transitTypeToString;
+import static android.window.TransitionInfo.FLAG_CROSS_PROFILE_OWNER_THUMBNAIL;
+import static android.window.TransitionInfo.FLAG_CROSS_PROFILE_WORK_THUMBNAIL;
import static android.window.TransitionInfo.FLAG_DISPLAY_HAS_ALERT_WINDOWS;
import static android.window.TransitionInfo.FLAG_IS_DISPLAY;
import static android.window.TransitionInfo.FLAG_IS_VOICE_INTERACTION;
@@ -903,11 +905,10 @@ public class DefaultTransitionHandler implements Transitions.TransitionHandler {
private void attachThumbnail(@NonNull ArrayList<Animator> animations,
@NonNull Runnable finishCallback, TransitionInfo.Change change,
TransitionInfo.AnimationOptions options, float cornerRadius) {
- final boolean isTask = change.getTaskInfo() != null;
final boolean isOpen = Transitions.isOpeningType(change.getMode());
final boolean isClose = Transitions.isClosingType(change.getMode());
if (isOpen) {
- if (options.getType() == ANIM_OPEN_CROSS_PROFILE_APPS && isTask) {
+ if (options.getType() == ANIM_OPEN_CROSS_PROFILE_APPS) {
attachCrossProfileThumbnailAnimation(animations, finishCallback, change,
cornerRadius);
} else if (options.getType() == ANIM_THUMBNAIL_SCALE_UP) {
@@ -922,8 +923,13 @@ public class DefaultTransitionHandler implements Transitions.TransitionHandler {
@NonNull Runnable finishCallback, TransitionInfo.Change change, float cornerRadius) {
final Rect bounds = change.getEndAbsBounds();
// Show the right drawable depending on the user we're transitioning to.
- final Drawable thumbnailDrawable = change.getTaskInfo().userId == mCurrentUserId
- ? mContext.getDrawable(R.drawable.ic_account_circle) : mEnterpriseThumbnailDrawable;
+ final Drawable thumbnailDrawable = change.hasFlags(FLAG_CROSS_PROFILE_OWNER_THUMBNAIL)
+ ? mContext.getDrawable(R.drawable.ic_account_circle)
+ : change.hasFlags(FLAG_CROSS_PROFILE_WORK_THUMBNAIL)
+ ? mEnterpriseThumbnailDrawable : null;
+ if (thumbnailDrawable == null) {
+ return;
+ }
final HardwareBuffer thumbnail = mTransitionAnimation.createCrossProfileAppsThumbnail(
thumbnailDrawable, bounds);
if (thumbnail == null) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/IShellTransitions.aidl b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/IShellTransitions.aidl
index bdcdb63d2cd6..cc4d268a0000 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/IShellTransitions.aidl
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/IShellTransitions.aidl
@@ -34,4 +34,9 @@ interface IShellTransitions {
* Unregisters a remote transition handler.
*/
oneway void unregisterRemote(in RemoteTransition remoteTransition) = 2;
+
+ /**
+ * Retrieves the apply-token used by transactions in Shell
+ */
+ IBinder getShellApplyToken() = 3;
}
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 29d25bc39223..d2e8624171f6 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
@@ -958,6 +958,11 @@ public class Transitions implements RemoteCallable<Transitions> {
transitions.mRemoteTransitionHandler.removeFiltered(remoteTransition);
});
}
+
+ @Override
+ public IBinder getShellApplyToken() {
+ return SurfaceControl.Transaction.getDefaultApplyToken();
+ }
}
private class SettingsObserver extends ContentObserver {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java
index dc3deb1a927c..8b13721ef428 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java
@@ -142,7 +142,7 @@ public class CaptionWindowDecoration extends WindowDecoration<WindowDecorLinearL
return;
}
- if (oldDecorationSurface != mDecorationContainerSurface) {
+ if (oldDecorationSurface != mDecorationContainerSurface || mDragResizeListener == null) {
closeDragResizeListener();
mDragResizeListener = new DragResizeInputListener(
mContext,
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/CommonAssertions.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/CommonAssertions.kt
index 330c9c95e484..cb74315732ab 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/CommonAssertions.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/CommonAssertions.kt
@@ -20,6 +20,7 @@ package com.android.wm.shell.flicker
import android.view.Surface
import com.android.server.wm.flicker.FlickerTestParameter
import com.android.server.wm.flicker.helpers.WindowUtils
+import com.android.server.wm.flicker.traces.layers.LayerTraceEntrySubject
import com.android.server.wm.flicker.traces.layers.LayersTraceSubject
import com.android.server.wm.traces.common.IComponentMatcher
import com.android.server.wm.traces.common.region.Region
@@ -94,25 +95,27 @@ fun FlickerTestParameter.layerKeepVisible(
fun FlickerTestParameter.splitAppLayerBoundsBecomesVisible(
component: IComponentMatcher,
- splitLeftTop: Boolean
+ landscapePosLeft: Boolean,
+ portraitPosTop: Boolean
) {
assertLayers {
- this.isInvisible(component)
+ this.notContains(SPLIT_SCREEN_DIVIDER_COMPONENT.or(component), isOptional = true)
.then()
- .isInvisible(SPLIT_SCREEN_DIVIDER_COMPONENT)
- .isVisible(component)
+ .isInvisible(SPLIT_SCREEN_DIVIDER_COMPONENT.or(component))
.then()
- .isVisible(SPLIT_SCREEN_DIVIDER_COMPONENT)
- .splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation)
+ .splitAppLayerBoundsSnapToDivider(
+ component, landscapePosLeft, portraitPosTop, endRotation)
}
}
fun FlickerTestParameter.splitAppLayerBoundsBecomesInvisible(
component: IComponentMatcher,
- splitLeftTop: Boolean
+ landscapePosLeft: Boolean,
+ portraitPosTop: Boolean
) {
assertLayers {
- this.splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation)
+ this.splitAppLayerBoundsSnapToDivider(
+ component, landscapePosLeft, portraitPosTop, endRotation)
.then()
.isVisible(component, true)
.then()
@@ -122,58 +125,96 @@ fun FlickerTestParameter.splitAppLayerBoundsBecomesInvisible(
fun FlickerTestParameter.splitAppLayerBoundsIsVisibleAtEnd(
component: IComponentMatcher,
- splitLeftTop: Boolean
+ landscapePosLeft: Boolean,
+ portraitPosTop: Boolean
) {
assertLayersEnd {
- val dividerRegion = layer(SPLIT_SCREEN_DIVIDER_COMPONENT).visibleRegion.region
- visibleRegion(component).coversAtMost(
- if (splitLeftTop) {
- getSplitLeftTopRegion(dividerRegion, endRotation)
- } else {
- getSplitRightBottomRegion(dividerRegion, endRotation)
- }
- )
+ splitAppLayerBoundsSnapToDivider(component, landscapePosLeft, portraitPosTop, endRotation)
}
}
fun FlickerTestParameter.splitAppLayerBoundsKeepVisible(
component: IComponentMatcher,
- splitLeftTop: Boolean
+ landscapePosLeft: Boolean,
+ portraitPosTop: Boolean
) {
assertLayers {
- this.splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation)
+ splitAppLayerBoundsSnapToDivider(component, landscapePosLeft, portraitPosTop, endRotation)
}
}
fun FlickerTestParameter.splitAppLayerBoundsChanges(
component: IComponentMatcher,
- splitLeftTop: Boolean
+ landscapePosLeft: Boolean,
+ portraitPosTop: Boolean
) {
assertLayers {
- if (splitLeftTop) {
- this.splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation)
+ if (landscapePosLeft) {
+ this.splitAppLayerBoundsSnapToDivider(
+ component, landscapePosLeft, portraitPosTop, endRotation)
.then()
.isInvisible(component)
.then()
- .splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation)
+ .splitAppLayerBoundsSnapToDivider(
+ component, landscapePosLeft, portraitPosTop, endRotation)
} else {
- this.splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation)
+ this.splitAppLayerBoundsSnapToDivider(
+ component, landscapePosLeft, portraitPosTop, endRotation)
}
}
}
fun LayersTraceSubject.splitAppLayerBoundsSnapToDivider(
component: IComponentMatcher,
- splitLeftTop: Boolean,
+ landscapePosLeft: Boolean,
+ portraitPosTop: Boolean,
rotation: Int
): LayersTraceSubject {
return invoke("splitAppLayerBoundsSnapToDivider") {
- val dividerRegion = it.layer(SPLIT_SCREEN_DIVIDER_COMPONENT).visibleRegion.region
- it.visibleRegion(component).coversAtMost(
- if (splitLeftTop) {
- getSplitLeftTopRegion(dividerRegion, rotation)
+ it.splitAppLayerBoundsSnapToDivider(component, landscapePosLeft, portraitPosTop, rotation)
+ }
+}
+
+fun LayerTraceEntrySubject.splitAppLayerBoundsSnapToDivider(
+ component: IComponentMatcher,
+ landscapePosLeft: Boolean,
+ portraitPosTop: Boolean,
+ rotation: Int
+): LayerTraceEntrySubject {
+ val displayBounds = WindowUtils.getDisplayBounds(rotation)
+ return invoke {
+ val dividerRegion = layer(SPLIT_SCREEN_DIVIDER_COMPONENT).visibleRegion.region
+ visibleRegion(component).coversAtMost(
+ if (displayBounds.width > displayBounds.height) {
+ if (landscapePosLeft) {
+ Region.from(
+ 0,
+ 0,
+ (dividerRegion.bounds.left + dividerRegion.bounds.right) / 2,
+ displayBounds.bounds.bottom)
+ } else {
+ Region.from(
+ (dividerRegion.bounds.left + dividerRegion.bounds.right) / 2,
+ 0,
+ displayBounds.bounds.right,
+ displayBounds.bounds.bottom
+ )
+ }
} else {
- getSplitRightBottomRegion(dividerRegion, rotation)
+ if (portraitPosTop) {
+ Region.from(
+ 0,
+ 0,
+ displayBounds.bounds.right,
+ (dividerRegion.bounds.top + dividerRegion.bounds.bottom) / 2)
+ } else {
+ Region.from(
+ 0,
+ (dividerRegion.bounds.top + dividerRegion.bounds.bottom) / 2,
+ displayBounds.bounds.right,
+ displayBounds.bounds.bottom
+ )
+ }
}
)
}
@@ -185,6 +226,10 @@ fun FlickerTestParameter.appWindowBecomesVisible(
assertWm {
this.isAppWindowInvisible(component)
.then()
+ .notContains(component, isOptional = true)
+ .then()
+ .isAppWindowInvisible(component, isOptional = true)
+ .then()
.isAppWindowVisible(component)
}
}
@@ -208,7 +253,7 @@ fun FlickerTestParameter.appWindowIsVisibleAtEnd(
}
fun FlickerTestParameter.appWindowKeepVisible(
- component: IComponentMatcher
+ component: IComponentMatcher
) {
assertWm {
this.isAppWindowVisible(component)
@@ -316,39 +361,3 @@ fun getSecondaryRegion(dividerRegion: Region, rotation: Int): Region {
)
}
}
-
-fun getSplitLeftTopRegion(dividerRegion: Region, rotation: Int): Region {
- val displayBounds = WindowUtils.getDisplayBounds(rotation)
- return if (displayBounds.width > displayBounds.height) {
- Region.from(
- 0,
- 0,
- (dividerRegion.bounds.left + dividerRegion.bounds.right) / 2,
- displayBounds.bounds.bottom)
- } else {
- Region.from(
- 0,
- 0,
- displayBounds.bounds.right,
- (dividerRegion.bounds.top + dividerRegion.bounds.bottom) / 2)
- }
-}
-
-fun getSplitRightBottomRegion(dividerRegion: Region, rotation: Int): Region {
- val displayBounds = WindowUtils.getDisplayBounds(rotation)
- return if (displayBounds.width > displayBounds.height) {
- Region.from(
- (dividerRegion.bounds.left + dividerRegion.bounds.right) / 2,
- 0,
- displayBounds.bounds.right,
- displayBounds.bounds.bottom
- )
- } else {
- Region.from(
- 0,
- (dividerRegion.bounds.top + dividerRegion.bounds.bottom) / 2,
- displayBounds.bounds.right,
- displayBounds.bounds.bottom
- )
- }
-}
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/helpers/SplitScreenHelper.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/helpers/SplitScreenHelper.kt
index 240e8711d43e..e7f9d9a9d73d 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/helpers/SplitScreenHelper.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/helpers/SplitScreenHelper.kt
@@ -105,6 +105,25 @@ class SplitScreenHelper(
.waitForAndVerify()
}
+ fun splitFromOverview(tapl: LauncherInstrumentation) {
+ // Note: The initial split position in landscape is different between tablet and phone.
+ // In landscape, tablet will let the first app split to right side, and phone will
+ // split to left side.
+ if (tapl.isTablet) {
+ tapl.workspace.switchToOverview().overviewActions
+ .clickSplit()
+ .currentTask
+ .open()
+ } else {
+ tapl.workspace.switchToOverview().currentTask
+ .tapMenu()
+ .tapSplitMenuItem()
+ .currentTask
+ .open()
+ }
+ SystemClock.sleep(TIMEOUT_MS)
+ }
+
fun dragFromNotificationToSplit(
instrumentation: Instrumentation,
device: UiDevice,
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt
index f69107eae638..d23881475ad6 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt
@@ -92,12 +92,12 @@ class CopyContentInSplit(testSpec: FlickerTestParameter) : SplitScreenBase(testS
@Presubmit
@Test
fun primaryAppBoundsKeepVisible() = testSpec.splitAppLayerBoundsKeepVisible(
- primaryApp, splitLeftTop = true)
+ primaryApp, landscapePosLeft = true, portraitPosTop = true)
@Presubmit
@Test
fun textEditAppBoundsKeepVisible() = testSpec.splitAppLayerBoundsKeepVisible(
- textEditApp, splitLeftTop = false)
+ textEditApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt
index cd92db74af95..ba40c2740bb1 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt
@@ -98,7 +98,7 @@ class DismissSplitScreenByDivider (testSpec: FlickerTestParameter) : SplitScreen
@Presubmit
@Test
fun primaryAppBoundsBecomesInvisible() = testSpec.splitAppLayerBoundsBecomesInvisible(
- primaryApp, splitLeftTop = false)
+ primaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt
index 127ac1e7162b..6828589656d6 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt
@@ -96,12 +96,12 @@ class DismissSplitScreenByGoHome(
@Presubmit
@Test
fun primaryAppBoundsBecomesInvisible() = testSpec.splitAppLayerBoundsBecomesInvisible(
- primaryApp, splitLeftTop = false)
+ primaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
fun secondaryAppBoundsBecomesInvisible() = testSpec.splitAppLayerBoundsBecomesInvisible(
- secondaryApp, splitLeftTop = true)
+ secondaryApp, landscapePosLeft = true, portraitPosTop = true)
@Presubmit
@Test
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt
index 0f4d98d69c00..9ac7c230096b 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt
@@ -108,12 +108,12 @@ class DragDividerToResize (testSpec: FlickerTestParameter) : SplitScreenBase(tes
@Presubmit
@Test
fun primaryAppBoundsChanges() = testSpec.splitAppLayerBoundsChanges(
- primaryApp, splitLeftTop = false)
+ primaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
fun secondaryAppBoundsChanges() = testSpec.splitAppLayerBoundsChanges(
- secondaryApp, splitLeftTop = true)
+ secondaryApp, landscapePosLeft = true, portraitPosTop = true)
/** {@inheritDoc} */
@Postsubmit
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt
index 9564d975194b..8401c1a910b8 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt
@@ -94,12 +94,12 @@ class EnterSplitScreenByDragFromAllApps(
@Presubmit
@Test
fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- primaryApp, splitLeftTop = false)
+ primaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
fun secondaryAppBoundsBecomesVisible() = testSpec.splitAppLayerBoundsBecomesVisible(
- secondaryApp, splitLeftTop = true)
+ secondaryApp, landscapePosLeft = true, portraitPosTop = true)
@Presubmit
@Test
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt
index 3b59716180b6..168afda119a9 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt
@@ -109,12 +109,12 @@ class EnterSplitScreenByDragFromNotification(
@Presubmit
@Test
fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- primaryApp, splitLeftTop = false)
+ primaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
fun secondaryAppBoundsBecomesVisible() = testSpec.splitAppLayerBoundsBecomesVisible(
- sendNotificationApp, splitLeftTop = true)
+ sendNotificationApp, landscapePosLeft = true, portraitPosTop = true)
@Presubmit
@Test
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt
index 3de98723e132..c1fce5f40b57 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt
@@ -97,12 +97,12 @@ class EnterSplitScreenByDragFromTaskbar(
@Presubmit
@Test
fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- primaryApp, splitLeftTop = false)
+ primaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
fun secondaryAppBoundsBecomesVisible() = testSpec.splitAppLayerBoundsBecomesVisible(
- secondaryApp, splitLeftTop = true)
+ secondaryApp, landscapePosLeft = true, portraitPosTop = true)
@Presubmit
@Test
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt
new file mode 100644
index 000000000000..8cb5d7c24ced
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.flicker.splitscreen
+
+import android.platform.test.annotations.Postsubmit
+import android.platform.test.annotations.Presubmit
+import androidx.test.filters.RequiresDevice
+import com.android.server.wm.flicker.FlickerParametersRunnerFactory
+import com.android.server.wm.flicker.FlickerTestParameter
+import com.android.server.wm.flicker.FlickerTestParameterFactory
+import com.android.server.wm.flicker.annotation.Group1
+import com.android.server.wm.flicker.dsl.FlickerBuilder
+import com.android.wm.shell.flicker.appWindowBecomesVisible
+import com.android.wm.shell.flicker.helpers.SplitScreenHelper
+import com.android.wm.shell.flicker.layerBecomesVisible
+import com.android.wm.shell.flicker.layerIsVisibleAtEnd
+import com.android.wm.shell.flicker.splitAppLayerBoundsBecomesVisible
+import com.android.wm.shell.flicker.splitAppLayerBoundsIsVisibleAtEnd
+import com.android.wm.shell.flicker.splitScreenDividerBecomesVisible
+import org.junit.FixMethodOrder
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.MethodSorters
+import org.junit.runners.Parameterized
+
+/**
+ * Test enter split screen from Overview.
+ *
+ * To run this test: `atest WMShellFlickerTests:EnterSplitScreenFromOverview`
+ */
+@RequiresDevice
+@RunWith(Parameterized::class)
+@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+@Group1
+class EnterSplitScreenFromOverview(testSpec: FlickerTestParameter) : SplitScreenBase(testSpec) {
+
+ override val transition: FlickerBuilder.() -> Unit
+ get() = {
+ super.transition(this)
+ setup {
+ eachRun {
+ tapl.workspace.switchToOverview().dismissAllTasks()
+ primaryApp.launchViaIntent(wmHelper)
+ secondaryApp.launchViaIntent(wmHelper)
+ tapl.goHome()
+ wmHelper.StateSyncBuilder()
+ .withAppTransitionIdle()
+ .withHomeActivityVisible()
+ .waitForAndVerify()
+ }
+ }
+ transitions {
+ SplitScreenHelper.splitFromOverview(tapl)
+ SplitScreenHelper.waitForSplitComplete(wmHelper, primaryApp, secondaryApp)
+ }
+ }
+
+ @Presubmit
+ @Test
+ fun splitScreenDividerBecomesVisible() = testSpec.splitScreenDividerBecomesVisible()
+
+ @Presubmit
+ @Test
+ fun primaryAppLayerIsVisibleAtEnd() = testSpec.layerIsVisibleAtEnd(primaryApp)
+
+ @Presubmit
+ @Test
+ fun secondaryAppLayerBecomesVisible() = testSpec.layerBecomesVisible(secondaryApp)
+
+ @Presubmit
+ @Test
+ fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
+ primaryApp, landscapePosLeft = tapl.isTablet, portraitPosTop = false)
+
+ @Presubmit
+ @Test
+ fun secondaryAppBoundsBecomesVisible() = testSpec.splitAppLayerBoundsBecomesVisible(
+ secondaryApp, landscapePosLeft = !tapl.isTablet, portraitPosTop = true)
+
+ @Presubmit
+ @Test
+ fun primaryAppWindowBecomesVisible() = testSpec.appWindowBecomesVisible(primaryApp)
+
+ @Presubmit
+ @Test
+ fun secondaryAppWindowBecomesVisible() = testSpec.appWindowBecomesVisible(secondaryApp)
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun entireScreenCovered() =
+ super.entireScreenCovered()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun navBarLayerIsVisibleAtStartAndEnd() =
+ super.navBarLayerIsVisibleAtStartAndEnd()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun navBarLayerPositionAtStartAndEnd() =
+ super.navBarLayerPositionAtStartAndEnd()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun navBarWindowIsAlwaysVisible() =
+ super.navBarWindowIsAlwaysVisible()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun statusBarLayerIsVisibleAtStartAndEnd() =
+ super.statusBarLayerIsVisibleAtStartAndEnd()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun statusBarLayerPositionAtStartAndEnd() =
+ super.statusBarLayerPositionAtStartAndEnd()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun statusBarWindowIsAlwaysVisible() =
+ super.statusBarWindowIsAlwaysVisible()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun taskBarLayerIsVisibleAtStartAndEnd() =
+ super.taskBarLayerIsVisibleAtStartAndEnd()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun taskBarWindowIsAlwaysVisible() =
+ super.taskBarWindowIsAlwaysVisible()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun visibleLayersShownMoreThanOneConsecutiveEntry() =
+ super.visibleLayersShownMoreThanOneConsecutiveEntry()
+
+ /** {@inheritDoc} */
+ @Postsubmit
+ @Test
+ override fun visibleWindowsShownMoreThanOneConsecutiveEntry() =
+ super.visibleWindowsShownMoreThanOneConsecutiveEntry()
+
+ companion object {
+ @Parameterized.Parameters(name = "{0}")
+ @JvmStatic
+ fun getParams(): List<FlickerTestParameter> {
+ return FlickerTestParameterFactory.getInstance().getConfigNonRotationTests(
+ repetitions = SplitScreenHelper.TEST_REPETITIONS)
+ }
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchAppByDoubleTapDivider.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchAppByDoubleTapDivider.kt
index bdfd9c7de32f..153056188d24 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchAppByDoubleTapDivider.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchAppByDoubleTapDivider.kt
@@ -94,12 +94,12 @@ class SwitchAppByDoubleTapDivider (testSpec: FlickerTestParameter) : SplitScreen
@Presubmit
@Test
fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- primaryApp, splitLeftTop = true)
+ primaryApp, landscapePosLeft = true, portraitPosTop = true)
@Presubmit
@Test
fun secondaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- secondaryApp, splitLeftTop = false)
+ secondaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt
index da954d97aec2..20544bd2fc2f 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt
@@ -98,12 +98,12 @@ class SwitchBackToSplitFromAnotherApp(testSpec: FlickerTestParameter) : SplitScr
@Presubmit
@Test
fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- primaryApp, splitLeftTop = false)
+ primaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
fun secondaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- secondaryApp, splitLeftTop = true)
+ secondaryApp, landscapePosLeft = true, portraitPosTop = true)
@Presubmit
@Test
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt
index db89ff52178b..5a8604f2dccc 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt
@@ -97,12 +97,12 @@ class SwitchBackToSplitFromHome(testSpec: FlickerTestParameter) : SplitScreenBas
@Presubmit
@Test
fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- primaryApp, splitLeftTop = false)
+ primaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
fun secondaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- secondaryApp, splitLeftTop = true)
+ secondaryApp, landscapePosLeft = true, portraitPosTop = true)
@Presubmit
@Test
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt
index c23cdb610671..adea66a49c46 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt
@@ -99,12 +99,12 @@ class SwitchBackToSplitFromRecent(testSpec: FlickerTestParameter) : SplitScreenB
@Presubmit
@Test
fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- primaryApp, splitLeftTop = false)
+ primaryApp, landscapePosLeft = false, portraitPosTop = false)
@Presubmit
@Test
fun secondaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd(
- secondaryApp, splitLeftTop = true)
+ secondaryApp, landscapePosLeft = true, portraitPosTop = true)
@Presubmit
@Test
diff --git a/packages/SettingsLib/MainSwitchPreference/res/layout-v33/settingslib_main_switch_bar.xml b/packages/SettingsLib/MainSwitchPreference/res/layout-v33/settingslib_main_switch_bar.xml
index 35d13230a3b7..2aa26e321a91 100644
--- a/packages/SettingsLib/MainSwitchPreference/res/layout-v33/settingslib_main_switch_bar.xml
+++ b/packages/SettingsLib/MainSwitchPreference/res/layout-v33/settingslib_main_switch_bar.xml
@@ -20,6 +20,11 @@
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="?android:attr/colorBackground"
+ android:minHeight="?android:attr/listPreferredItemHeight"
+ android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
+ android:paddingStart="?android:attr/listPreferredItemPaddingStart"
+ android:paddingTop="@dimen/settingslib_switchbar_margin"
+ android:paddingBottom="@dimen/settingslib_switchbar_margin"
android:orientation="vertical">
<LinearLayout
@@ -27,7 +32,6 @@
android:minHeight="@dimen/settingslib_min_switch_bar_height"
android:layout_height="wrap_content"
android:layout_width="match_parent"
- android:layout_margin="@dimen/settingslib_switchbar_margin"
android:paddingStart="@dimen/settingslib_switchbar_padding_left"
android:paddingEnd="@dimen/settingslib_switchbar_padding_right">
diff --git a/packages/SettingsLib/Spa/.idea/codeStyles/Project.xml b/packages/SettingsLib/Spa/.idea/codeStyles/Project.xml
index cb757d34dfb4..9578fcf0f4cd 100644
--- a/packages/SettingsLib/Spa/.idea/codeStyles/Project.xml
+++ b/packages/SettingsLib/Spa/.idea/codeStyles/Project.xml
@@ -1,6 +1,15 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JetCodeStyleSettings>
+ <option name="PACKAGES_TO_USE_STAR_IMPORTS">
+ <value />
+ </option>
+ <option name="PACKAGES_IMPORT_LAYOUT">
+ <value>
+ <package name="" alias="false" withSubpackages="true" />
+ <package name="" alias="true" withSubpackages="true" />
+ </value>
+ </option>
<option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="2147483647" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="2147483647" />
</JetCodeStyleSettings>
diff --git a/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/SettingsPagerPage.kt b/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/SettingsPagerPage.kt
index 5351ea65da47..df48517fb1fb 100644
--- a/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/SettingsPagerPage.kt
+++ b/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/SettingsPagerPage.kt
@@ -17,11 +17,7 @@
package com.android.settingslib.spa.gallery.page
import android.os.Bundle
-import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.android.settingslib.spa.framework.api.SettingsPageProvider
import com.android.settingslib.spa.framework.compose.navigator
@@ -29,7 +25,10 @@ import com.android.settingslib.spa.framework.theme.SettingsTheme
import com.android.settingslib.spa.widget.preference.Preference
import com.android.settingslib.spa.widget.preference.PreferenceModel
import com.android.settingslib.spa.widget.scaffold.SettingsPager
-import com.android.settingslib.spa.widget.ui.SettingsTitle
+import com.android.settingslib.spa.widget.scaffold.SettingsScaffold
+import com.android.settingslib.spa.widget.ui.PlaceholderTitle
+
+private const val TITLE = "Sample SettingsPager"
object SettingsPagerPageProvider : SettingsPageProvider {
override val name = "SettingsPager"
@@ -42,7 +41,7 @@ object SettingsPagerPageProvider : SettingsPageProvider {
@Composable
fun EntryItem() {
Preference(object : PreferenceModel {
- override val title = "Sample SettingsPager"
+ override val title = TITLE
override val onClick = navigator(name)
})
}
@@ -50,9 +49,9 @@ object SettingsPagerPageProvider : SettingsPageProvider {
@Composable
private fun SettingsPagerPage() {
- SettingsPager(listOf("Personal", "Work")) {
- Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- SettingsTitle(title = "Page $it")
+ SettingsScaffold(title = TITLE) {
+ SettingsPager(listOf("Personal", "Work")) {
+ PlaceholderTitle("Page $it")
}
}
}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/LogCompositions.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/LogCompositions.kt
new file mode 100644
index 000000000000..4eef2a8ffbbf
--- /dev/null
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/LogCompositions.kt
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spa.framework.compose
+
+import android.util.Log
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.SideEffect
+import androidx.compose.runtime.remember
+
+const val ENABLE_LOG_COMPOSITIONS = false
+
+data class LogCompositionsRef(var count: Int)
+
+// Note the inline function below which ensures that this function is essentially
+// copied at the call site to ensure that its logging only recompositions from the
+// original call site.
+@Suppress("NOTHING_TO_INLINE")
+@Composable
+inline fun LogCompositions(tag: String, msg: String) {
+ if (ENABLE_LOG_COMPOSITIONS) {
+ val ref = remember { LogCompositionsRef(0) }
+ SideEffect { ref.count++ }
+ Log.d(tag, "Compositions $msg: ${ref.count}")
+ }
+}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Pager.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Pager.kt
new file mode 100644
index 000000000000..bf338574c42d
--- /dev/null
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Pager.kt
@@ -0,0 +1,339 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spa.framework.compose
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.calculateEndPadding
+import androidx.compose.foundation.layout.calculateStartPadding
+import androidx.compose.foundation.layout.wrapContentSize
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.Stable
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.snapshotFlow
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
+import androidx.compose.ui.input.nestedscroll.NestedScrollSource
+import androidx.compose.ui.input.nestedscroll.nestedScroll
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalLayoutDirection
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.Velocity
+import androidx.compose.ui.unit.dp
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.drop
+import kotlinx.coroutines.flow.filter
+
+/**
+ * *************************************************************************************************
+ * This file was forked from
+ * https://github.com/google/accompanist/blob/main/pager/src/main/java/com/google/accompanist/pager/Pager.kt
+ * and will be removed once it lands in AndroidX.
+ */
+
+/**
+ * A horizontally scrolling layout that allows users to flip between items to the left and right.
+ *
+ * @sample com.google.accompanist.sample.pager.HorizontalPagerSample
+ *
+ * @param count the number of pages.
+ * @param modifier the modifier to apply to this layout.
+ * @param state the state object to be used to control or observe the pager's state.
+ * @param reverseLayout reverse the direction of scrolling and layout, when `true` items will be
+ * composed from the end to the start and [PagerState.currentPage] == 0 will mean
+ * the first item is located at the end.
+ * @param itemSpacing horizontal spacing to add between items.
+ * @param key the scroll position will be maintained based on the key, which means if you
+ * add/remove items before the current visible item the item with the given key will be kept as the
+ * first visible one.
+ * @param content a block which describes the content. Inside this block you can reference
+ * [PagerScope.currentPage] and other properties in [PagerScope].
+ */
+@Composable
+fun HorizontalPager(
+ count: Int,
+ modifier: Modifier = Modifier,
+ state: PagerState = rememberPagerState(),
+ reverseLayout: Boolean = false,
+ itemSpacing: Dp = 0.dp,
+ contentPadding: PaddingValues = PaddingValues(0.dp),
+ verticalAlignment: Alignment.Vertical = Alignment.CenterVertically,
+ key: ((page: Int) -> Any)? = null,
+ content: @Composable PagerScope.(page: Int) -> Unit,
+) {
+ Pager(
+ count = count,
+ state = state,
+ modifier = modifier,
+ isVertical = false,
+ reverseLayout = reverseLayout,
+ itemSpacing = itemSpacing,
+ verticalAlignment = verticalAlignment,
+ key = key,
+ contentPadding = contentPadding,
+ content = content
+ )
+}
+
+/**
+ * A vertically scrolling layout that allows users to flip between items to the top and bottom.
+ *
+ * @sample com.google.accompanist.sample.pager.VerticalPagerSample
+ *
+ * @param count the number of pages.
+ * @param modifier the modifier to apply to this layout.
+ * @param state the state object to be used to control or observe the pager's state.
+ * @param reverseLayout reverse the direction of scrolling and layout, when `true` items will be
+ * composed from the bottom to the top and [PagerState.currentPage] == 0 will mean
+ * the first item is located at the bottom.
+ * @param itemSpacing vertical spacing to add between items.
+ * @param key the scroll position will be maintained based on the key, which means if you
+ * add/remove items before the current visible item the item with the given key will be kept as the
+ * first visible one.
+ * @param content a block which describes the content. Inside this block you can reference
+ * [PagerScope.currentPage] and other properties in [PagerScope].
+ */
+@Composable
+fun VerticalPager(
+ count: Int,
+ modifier: Modifier = Modifier,
+ state: PagerState = rememberPagerState(),
+ reverseLayout: Boolean = false,
+ itemSpacing: Dp = 0.dp,
+ contentPadding: PaddingValues = PaddingValues(0.dp),
+ horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally,
+ key: ((page: Int) -> Any)? = null,
+ content: @Composable() (PagerScope.(page: Int) -> Unit),
+) {
+ Pager(
+ count = count,
+ state = state,
+ modifier = modifier,
+ isVertical = true,
+ reverseLayout = reverseLayout,
+ itemSpacing = itemSpacing,
+ horizontalAlignment = horizontalAlignment,
+ key = key,
+ contentPadding = contentPadding,
+ content = content
+ )
+}
+
+@Composable
+internal fun Pager(
+ count: Int,
+ modifier: Modifier,
+ state: PagerState,
+ reverseLayout: Boolean,
+ itemSpacing: Dp,
+ isVertical: Boolean,
+ key: ((page: Int) -> Any)?,
+ contentPadding: PaddingValues,
+ verticalAlignment: Alignment.Vertical = Alignment.CenterVertically,
+ horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally,
+ content: @Composable PagerScope.(page: Int) -> Unit,
+) {
+ require(count >= 0) { "pageCount must be >= 0" }
+
+ LaunchedEffect(count) {
+ state.currentPage = minOf(count - 1, state.currentPage).coerceAtLeast(0)
+ }
+
+ // Once a fling (scroll) has finished, notify the state
+ LaunchedEffect(state) {
+ // When a 'scroll' has finished, notify the state
+ snapshotFlow { state.isScrollInProgress }
+ .filter { !it }
+ // initially isScrollInProgress is false as well and we want to start receiving
+ // the events only after the real scroll happens.
+ .drop(1)
+ .collect { state.onScrollFinished() }
+ }
+ LaunchedEffect(state) {
+ snapshotFlow { state.mostVisiblePageLayoutInfo?.index }
+ .distinctUntilChanged()
+ .collect { state.updateCurrentPageBasedOnLazyListState() }
+ }
+ val density = LocalDensity.current
+ val layoutDirection = LocalLayoutDirection.current
+ LaunchedEffect(density, contentPadding, isVertical, layoutDirection, reverseLayout, state) {
+ with(density) {
+ // this should be exposed on LazyListLayoutInfo instead. b/200920410
+ state.afterContentPadding = if (isVertical) {
+ if (!reverseLayout) {
+ contentPadding.calculateBottomPadding()
+ } else {
+ contentPadding.calculateTopPadding()
+ }
+ } else {
+ if (!reverseLayout) {
+ contentPadding.calculateEndPadding(layoutDirection)
+ } else {
+ contentPadding.calculateStartPadding(layoutDirection)
+ }
+ }.roundToPx()
+ }
+ }
+
+ val pagerScope = remember(state) { PagerScopeImpl(state) }
+
+ // We only consume nested flings in the main-axis, allowing cross-axis flings to propagate
+ // as normal
+ val consumeFlingNestedScrollConnection = remember(isVertical) {
+ ConsumeFlingNestedScrollConnection(
+ consumeHorizontal = !isVertical,
+ consumeVertical = isVertical,
+ )
+ }
+
+ if (isVertical) {
+ LazyColumn(
+ state = state.lazyListState,
+ verticalArrangement = Arrangement.spacedBy(itemSpacing, verticalAlignment),
+ horizontalAlignment = horizontalAlignment,
+ reverseLayout = reverseLayout,
+ contentPadding = contentPadding,
+ modifier = modifier,
+ ) {
+ items(
+ count = count,
+ key = key,
+ ) { page ->
+ Box(
+ Modifier
+ // We don't any nested flings to continue in the pager, so we add a
+ // connection which consumes them.
+ // See: https://github.com/google/accompanist/issues/347
+ .nestedScroll(connection = consumeFlingNestedScrollConnection)
+ // Constraint the content height to be <= than the height of the pager.
+ .fillParentMaxHeight()
+ .wrapContentSize()
+ ) {
+ pagerScope.content(page)
+ }
+ }
+ }
+ } else {
+ LazyRow(
+ state = state.lazyListState,
+ verticalAlignment = verticalAlignment,
+ horizontalArrangement = Arrangement.spacedBy(itemSpacing, horizontalAlignment),
+ reverseLayout = reverseLayout,
+ contentPadding = contentPadding,
+ modifier = modifier,
+ ) {
+ items(
+ count = count,
+ key = key,
+ ) { page ->
+ Box(
+ Modifier
+ // We don't any nested flings to continue in the pager, so we add a
+ // connection which consumes them.
+ // See: https://github.com/google/accompanist/issues/347
+ .nestedScroll(connection = consumeFlingNestedScrollConnection)
+ // Constraint the content width to be <= than the width of the pager.
+ .fillParentMaxWidth()
+ .wrapContentSize()
+ ) {
+ pagerScope.content(page)
+ }
+ }
+ }
+ }
+}
+
+private class ConsumeFlingNestedScrollConnection(
+ private val consumeHorizontal: Boolean,
+ private val consumeVertical: Boolean,
+) : NestedScrollConnection {
+ override fun onPostScroll(
+ consumed: Offset,
+ available: Offset,
+ source: NestedScrollSource
+ ): Offset = when (source) {
+ // We can consume all resting fling scrolls so that they don't propagate up to the
+ // Pager
+ NestedScrollSource.Fling -> available.consume(consumeHorizontal, consumeVertical)
+ else -> Offset.Zero
+ }
+
+ override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
+ // We can consume all post fling velocity on the main-axis
+ // so that it doesn't propagate up to the Pager
+ return available.consume(consumeHorizontal, consumeVertical)
+ }
+}
+
+private fun Offset.consume(
+ consumeHorizontal: Boolean,
+ consumeVertical: Boolean,
+): Offset = Offset(
+ x = if (consumeHorizontal) this.x else 0f,
+ y = if (consumeVertical) this.y else 0f,
+)
+
+private fun Velocity.consume(
+ consumeHorizontal: Boolean,
+ consumeVertical: Boolean,
+): Velocity = Velocity(
+ x = if (consumeHorizontal) this.x else 0f,
+ y = if (consumeVertical) this.y else 0f,
+)
+
+/**
+ * Scope for [HorizontalPager] content.
+ */
+@Stable
+interface PagerScope {
+ /**
+ * Returns the current selected page
+ */
+ val currentPage: Int
+
+ /**
+ * The current offset from the start of [currentPage], as a ratio of the page width.
+ */
+ val currentPageOffset: Float
+}
+
+private class PagerScopeImpl(
+ private val state: PagerState,
+) : PagerScope {
+ override val currentPage: Int get() = state.currentPage
+ override val currentPageOffset: Float get() = state.currentPageOffset
+}
+
+/**
+ * Calculate the offset for the given [page] from the current scroll position. This is useful
+ * when using the scroll position to apply effects or animations to items.
+ *
+ * The returned offset can positive or negative, depending on whether which direction the [page] is
+ * compared to the current scroll position.
+ *
+ * @sample com.google.accompanist.sample.pager.HorizontalPagerWithOffsetTransition
+ */
+fun PagerScope.calculateCurrentOffsetForPage(page: Int): Float {
+ return (currentPage - page) + currentPageOffset
+}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/PagerState.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/PagerState.kt
new file mode 100644
index 000000000000..21ba11739af0
--- /dev/null
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/PagerState.kt
@@ -0,0 +1,318 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spa.framework.compose
+
+import androidx.annotation.FloatRange
+import androidx.annotation.IntRange
+import androidx.compose.foundation.MutatePriority
+import androidx.compose.foundation.gestures.ScrollScope
+import androidx.compose.foundation.gestures.ScrollableState
+import androidx.compose.foundation.interaction.InteractionSource
+import androidx.compose.foundation.lazy.LazyListItemInfo
+import androidx.compose.foundation.lazy.LazyListState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.Stable
+import androidx.compose.runtime.derivedStateOf
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.saveable.Saver
+import androidx.compose.runtime.saveable.listSaver
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import kotlin.math.abs
+import kotlin.math.absoluteValue
+import kotlin.math.roundToInt
+
+/**
+ * *************************************************************************************************
+ * This file was forked from
+ * https://github.com/google/accompanist/blob/main/pager/src/main/java/com/google/accompanist/pager/PagerState.kt
+ * and will be removed once it lands in AndroidX.
+ */
+
+/**
+ * Creates a [PagerState] that is remembered across compositions.
+ *
+ * Changes to the provided values for [initialPage] will **not** result in the state being
+ * recreated or changed in any way if it has already
+ * been created.
+ *
+ * @param initialPage the initial value for [PagerState.currentPage]
+ */
+@Composable
+fun rememberPagerState(
+ @IntRange(from = 0) initialPage: Int = 0,
+): PagerState = rememberSaveable(saver = PagerState.Saver) {
+ PagerState(
+ currentPage = initialPage,
+ )
+}
+
+/**
+ * A state object that can be hoisted to control and observe scrolling for [HorizontalPager].
+ *
+ * In most cases, this will be created via [rememberPagerState].
+ *
+ * @param currentPage the initial value for [PagerState.currentPage]
+ */
+@Stable
+class PagerState(
+ @IntRange(from = 0) currentPage: Int = 0,
+) : ScrollableState {
+ // Should this be public?
+ internal val lazyListState = LazyListState(firstVisibleItemIndex = currentPage)
+
+ private var _currentPage by mutableStateOf(currentPage)
+
+ // finds the page which has larger visible area within the viewport not including paddings
+ internal val mostVisiblePageLayoutInfo: LazyListItemInfo?
+ get() {
+ val layoutInfo = lazyListState.layoutInfo
+ return layoutInfo.visibleItemsInfo.maxByOrNull {
+ val start = maxOf(it.offset, 0)
+ val end = minOf(
+ it.offset + it.size, layoutInfo.viewportEndOffset - afterContentPadding)
+ end - start
+ }
+ }
+
+ internal var afterContentPadding = 0
+
+ private val currentPageLayoutInfo: LazyListItemInfo?
+ get() = lazyListState.layoutInfo.visibleItemsInfo.lastOrNull {
+ it.index == currentPage
+ }
+
+ /**
+ * [InteractionSource] that will be used to dispatch drag events when this
+ * list is being dragged. If you want to know whether the fling (or animated scroll) is in
+ * progress, use [isScrollInProgress].
+ */
+ val interactionSource: InteractionSource
+ get() = lazyListState.interactionSource
+
+ /**
+ * The number of pages to display.
+ */
+ @get:IntRange(from = 0)
+ val pageCount: Int by derivedStateOf {
+ lazyListState.layoutInfo.totalItemsCount
+ }
+
+ /**
+ * The index of the currently selected page. This may not be the page which is
+ * currently displayed on screen.
+ *
+ * To update the scroll position, use [scrollToPage] or [animateScrollToPage].
+ */
+ @get:IntRange(from = 0)
+ var currentPage: Int
+ get() = _currentPage
+ internal set(value) {
+ if (value != _currentPage) {
+ _currentPage = value
+ }
+ }
+
+ /**
+ * The current offset from the start of [currentPage], as a ratio of the page width.
+ *
+ * To update the scroll position, use [scrollToPage] or [animateScrollToPage].
+ */
+ val currentPageOffset: Float by derivedStateOf {
+ currentPageLayoutInfo?.let {
+ // We coerce since itemSpacing can make the offset > 1f.
+ // We don't want to count spacing in the offset so cap it to 1f
+ (-it.offset / it.size.toFloat()).coerceIn(-1f, 1f)
+ } ?: 0f
+ }
+
+ /**
+ * The target page for any on-going animations.
+ */
+ private var animationTargetPage: Int? by mutableStateOf(null)
+
+ /**
+ * Animate (smooth scroll) to the given page to the middle of the viewport.
+ *
+ * Cancels the currently running scroll, if any, and suspends until the cancellation is
+ * complete.
+ *
+ * @param page the page to animate to. Must be >= 0.
+ * @param pageOffset the percentage of the page size to offset, from the start of [page].
+ * Must be in the range -1f..1f.
+ */
+ suspend fun animateScrollToPage(
+ @IntRange(from = 0) page: Int,
+ @FloatRange(from = -1.0, to = 1.0) pageOffset: Float = 0f,
+ ) {
+ requireCurrentPage(page, "page")
+ requireCurrentPageOffset(pageOffset, "pageOffset")
+ try {
+ animationTargetPage = page
+
+ // pre-jump to nearby item for long jumps as an optimization
+ // the same trick is done in ViewPager2
+ val oldPage = lazyListState.firstVisibleItemIndex
+ if (abs(page - oldPage) > 3) {
+ lazyListState.scrollToItem(if (page > oldPage) page - 3 else page + 3)
+ }
+
+ if (pageOffset.absoluteValue <= 0.005f) {
+ // If the offset is (close to) zero, just call animateScrollToItem and we're done
+ lazyListState.animateScrollToItem(index = page)
+ } else {
+ // Else we need to figure out what the offset is in pixels...
+ lazyListState.scroll { } // this will await for the first layout.
+ val layoutInfo = lazyListState.layoutInfo
+ var target = layoutInfo.visibleItemsInfo
+ .firstOrNull { it.index == page }
+
+ if (target != null) {
+ // If we have access to the target page layout, we can calculate the pixel
+ // offset from the size
+ lazyListState.animateScrollToItem(
+ index = page,
+ scrollOffset = (target.size * pageOffset).roundToInt()
+ )
+ } else if (layoutInfo.visibleItemsInfo.isNotEmpty()) {
+ // If we don't, we use the current page size as a guide
+ val currentSize = layoutInfo.visibleItemsInfo.first().size
+ lazyListState.animateScrollToItem(
+ index = page,
+ scrollOffset = (currentSize * pageOffset).roundToInt()
+ )
+
+ // The target should be visible now
+ target = lazyListState.layoutInfo.visibleItemsInfo.firstOrNull {
+ it.index == page
+ }
+
+ if (target != null && target.size != currentSize) {
+ // If the size we used for calculating the offset differs from the actual
+ // target page size, we need to scroll again. This doesn't look great,
+ // but there's not much else we can do.
+ lazyListState.animateScrollToItem(
+ index = page,
+ scrollOffset = (target.size * pageOffset).roundToInt()
+ )
+ }
+ }
+ }
+ } finally {
+ // We need to manually call this, as the `animateScrollToItem` call above will happen
+ // in 1 frame, which is usually too fast for the LaunchedEffect in Pager to detect
+ // the change. This is especially true when running unit tests.
+ onScrollFinished()
+ }
+ }
+
+ /**
+ * Instantly brings the item at [page] to the middle of the viewport.
+ *
+ * Cancels the currently running scroll, if any, and suspends until the cancellation is
+ * complete.
+ *
+ * @param page the page to snap to. Must be >= 0.
+ * @param pageOffset the percentage of the page size to offset, from the start of [page].
+ * Must be in the range -1f..1f.
+ */
+ suspend fun scrollToPage(
+ @IntRange(from = 0) page: Int,
+ @FloatRange(from = -1.0, to = 1.0) pageOffset: Float = 0f,
+ ) {
+ requireCurrentPage(page, "page")
+ requireCurrentPageOffset(pageOffset, "pageOffset")
+ try {
+ animationTargetPage = page
+
+ // First scroll to the given page. It will now be laid out at offset 0
+ lazyListState.scrollToItem(index = page)
+ updateCurrentPageBasedOnLazyListState()
+
+ // If we have a start spacing, we need to offset (scroll) by that too
+ if (pageOffset.absoluteValue > 0.0001f) {
+ currentPageLayoutInfo?.let {
+ scroll {
+ scrollBy(it.size * pageOffset)
+ }
+ }
+ }
+ } finally {
+ // We need to manually call this, as the `scroll` call above will happen in 1 frame,
+ // which is usually too fast for the LaunchedEffect in Pager to detect the change.
+ // This is especially true when running unit tests.
+ onScrollFinished()
+ }
+ }
+
+ internal fun updateCurrentPageBasedOnLazyListState() {
+ // Then update the current page to our layout page
+ mostVisiblePageLayoutInfo?.let {
+ currentPage = it.index
+ }
+ }
+
+ internal fun onScrollFinished() {
+ // Clear the animation target page
+ animationTargetPage = null
+ }
+
+ override suspend fun scroll(
+ scrollPriority: MutatePriority,
+ block: suspend ScrollScope.() -> Unit
+ ) = lazyListState.scroll(scrollPriority, block)
+
+ override fun dispatchRawDelta(delta: Float): Float {
+ return lazyListState.dispatchRawDelta(delta)
+ }
+
+ override val isScrollInProgress: Boolean
+ get() = lazyListState.isScrollInProgress
+
+ override fun toString(): String = "PagerState(" +
+ "pageCount=$pageCount, " +
+ "currentPage=$currentPage, " +
+ "currentPageOffset=$currentPageOffset" +
+ ")"
+
+ private fun requireCurrentPage(value: Int, name: String) {
+ require(value >= 0) { "$name[$value] must be >= 0" }
+ }
+
+ private fun requireCurrentPageOffset(value: Float, name: String) {
+ require(value in -1f..1f) { "$name must be >= 0 and <= 1" }
+ }
+
+ companion object {
+ /**
+ * The default [Saver] implementation for [PagerState].
+ */
+ val Saver: Saver<PagerState, *> = listSaver(
+ save = {
+ listOf<Any>(
+ it.currentPage,
+ )
+ },
+ restore = {
+ PagerState(
+ currentPage = it[0] as Int,
+ )
+ }
+ )
+ }
+}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsDimension.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsDimension.kt
index 7d3e10768e46..965436847c64 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsDimension.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsDimension.kt
@@ -32,4 +32,10 @@ object SettingsDimension {
bottom = itemPaddingVertical,
)
val itemPaddingAround = 8.dp
+
+ /** The size when app icon is displayed in list. */
+ val appIconItemSize = 32.dp
+
+ /** The size when app icon is displayed in App info page. */
+ val appIconInfoSize = 48.dp
}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Collections.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Collections.kt
new file mode 100644
index 000000000000..ba253368d505
--- /dev/null
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Collections.kt
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spa.framework.util
+
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+
+suspend inline fun <R, T> Iterable<T>.asyncMap(crossinline transform: (T) -> R): List<R> =
+ coroutineScope {
+ map { item ->
+ async { transform(item) }
+ }.awaitAll()
+ }
+
+suspend inline fun <T> Iterable<T>.asyncFilter(crossinline predicate: (T) -> Boolean): List<T> =
+ asyncMap { item -> item to predicate(item) }
+ .filter { it.second }
+ .map { it.first }
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Flows.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Flows.kt
new file mode 100644
index 000000000000..999d8d7dd16a
--- /dev/null
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Flows.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spa.framework.util
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.State
+import androidx.compose.runtime.snapshotFlow
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChangedBy
+import kotlinx.coroutines.flow.filterNotNull
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.map
+
+inline fun <T, R> Flow<List<T>>.asyncMapItem(crossinline transform: (T) -> R): Flow<List<R>> =
+ map { list -> list.asyncMap(transform) }
+
+@OptIn(ExperimentalCoroutinesApi::class)
+inline fun <T, R> Flow<T>.mapState(crossinline block: (T) -> State<R>): Flow<R> =
+ flatMapLatest { snapshotFlow { block(it).value } }
+
+fun <T1, T2> Flow<T1>.waitFirst(flow: Flow<T2>): Flow<T1> =
+ combine(flow.distinctUntilChangedBy {}) { value, _ -> value }
+
+class StateFlowBridge<T> {
+ private val stateFlow = MutableStateFlow<T?>(null)
+ val flow = stateFlow.filterNotNull()
+
+ fun setIfAbsent(value: T) {
+ if (stateFlow.value == null) {
+ stateFlow.value = value
+ }
+ }
+
+ @Composable
+ fun Sync(state: State<T>) {
+ LaunchedEffect(state.value) {
+ stateFlow.value = state.value
+ }
+ }
+}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/Actions.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/Actions.kt
index 0a41a1a95936..c9602543b364 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/Actions.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/Actions.kt
@@ -18,6 +18,7 @@ package com.android.settingslib.spa.widget.scaffold
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ArrowBack
+import androidx.compose.material.icons.outlined.MoreVert
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
@@ -44,3 +45,15 @@ private fun BackAction(contentDescription: String, onClick: () -> Unit) {
)
}
}
+
+@Composable
+fun MoreOptionsAction(onClick: () -> Unit) {
+ IconButton(onClick) {
+ Icon(
+ imageVector = Icons.Outlined.MoreVert,
+ contentDescription = stringResource(
+ id = androidx.appcompat.R.string.abc_action_menu_overflow_description,
+ )
+ )
+ }
+}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/RegularScaffold.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/RegularScaffold.kt
index 3325d5382f2e..9a17b2a8cb78 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/RegularScaffold.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/RegularScaffold.kt
@@ -22,15 +22,10 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
-import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
-import androidx.compose.material3.SmallTopAppBar
-import androidx.compose.material3.Text
-import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
-import com.android.settingslib.spa.framework.theme.SettingsDimension
import com.android.settingslib.spa.framework.theme.SettingsTheme
/**
@@ -39,28 +34,13 @@ import com.android.settingslib.spa.framework.theme.SettingsTheme
* For example, this is for the pages with some preferences and is scrollable when the items out of
* the screen.
*/
-@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RegularScaffold(
title: String,
actions: @Composable RowScope.() -> Unit = {},
content: @Composable () -> Unit,
) {
- Scaffold(
- topBar = {
- SmallTopAppBar(
- title = {
- Text(
- text = title,
- modifier = Modifier.padding(SettingsDimension.itemPaddingAround),
- )
- },
- navigationIcon = { NavigateUp() },
- actions = actions,
- colors = settingsTopAppBarColors(),
- )
- },
- ) { paddingValues ->
+ SettingsScaffold(title, actions) { paddingValues ->
Column(Modifier.verticalScroll(rememberScrollState())) {
Spacer(Modifier.padding(paddingValues))
content()
@@ -68,12 +48,6 @@ fun RegularScaffold(
}
}
-@Composable
-internal fun settingsTopAppBarColors() = TopAppBarDefaults.largeTopAppBarColors(
- containerColor = SettingsTheme.colorScheme.surfaceHeader,
- scrolledContainerColor = SettingsTheme.colorScheme.surfaceHeader,
-)
-
@Preview
@Composable
private fun RegularScaffoldPreview() {
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsPager.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsPager.kt
index 1ec2390741ed..e0e9b951065b 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsPager.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsPager.kt
@@ -20,13 +20,14 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.TabRow
import androidx.compose.runtime.Composable
-import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.saveable.rememberSaveable
-import androidx.compose.runtime.setValue
+import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
+import com.android.settingslib.spa.framework.compose.HorizontalPager
+import com.android.settingslib.spa.framework.compose.rememberPagerState
import com.android.settingslib.spa.framework.theme.SettingsDimension
+import kotlin.math.absoluteValue
+import kotlinx.coroutines.launch
@Composable
fun SettingsPager(titles: List<String>, content: @Composable (page: Int) -> Unit) {
@@ -37,10 +38,11 @@ fun SettingsPager(titles: List<String>, content: @Composable (page: Int) -> Unit
}
Column {
- var currentPage by rememberSaveable { mutableStateOf(0) }
+ val coroutineScope = rememberCoroutineScope()
+ val pagerState = rememberPagerState()
TabRow(
- selectedTabIndex = currentPage,
+ selectedTabIndex = pagerState.currentPage,
modifier = Modifier.padding(horizontal = SettingsDimension.itemPaddingEnd),
containerColor = Color.Transparent,
indicator = {},
@@ -49,12 +51,19 @@ fun SettingsPager(titles: List<String>, content: @Composable (page: Int) -> Unit
titles.forEachIndexed { page, title ->
SettingsTab(
title = title,
- selected = currentPage == page,
- onClick = { currentPage = page },
+ selected = pagerState.currentPage == page,
+ currentPageOffset = pagerState.currentPageOffset.absoluteValue,
+ onClick = {
+ coroutineScope.launch {
+ pagerState.animateScrollToPage(page)
+ }
+ },
)
}
}
- content(currentPage)
+ HorizontalPager(count = titles.size, state = pagerState) { page ->
+ content(page)
+ }
}
}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffold.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffold.kt
new file mode 100644
index 000000000000..ee453f246623
--- /dev/null
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffold.kt
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spa.widget.scaffold
+
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.RowScope
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.SmallTopAppBar
+import androidx.compose.material3.Text
+import androidx.compose.material3.TopAppBarDefaults
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.tooling.preview.Preview
+import com.android.settingslib.spa.framework.theme.SettingsDimension
+import com.android.settingslib.spa.framework.theme.SettingsTheme
+
+/**
+ * A [Scaffold] which content is can be full screen when needed.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun SettingsScaffold(
+ title: String,
+ actions: @Composable RowScope.() -> Unit = {},
+ content: @Composable (PaddingValues) -> Unit,
+) {
+ Scaffold(
+ topBar = {
+ SmallTopAppBar(
+ title = {
+ Text(
+ text = title,
+ modifier = Modifier.padding(SettingsDimension.itemPaddingAround),
+ )
+ },
+ navigationIcon = { NavigateUp() },
+ actions = actions,
+ colors = settingsTopAppBarColors(),
+ )
+ },
+ content = content,
+ )
+}
+
+@Composable
+internal fun settingsTopAppBarColors() = TopAppBarDefaults.largeTopAppBarColors(
+ containerColor = SettingsTheme.colorScheme.surfaceHeader,
+ scrolledContainerColor = SettingsTheme.colorScheme.surfaceHeader,
+)
+
+@Preview
+@Composable
+private fun SettingsScaffoldPreview() {
+ SettingsTheme {
+ SettingsScaffold(title = "Display") {}
+ }
+}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsTab.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsTab.kt
index 16d8dbc9bf74..30a4349e942f 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsTab.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsTab.kt
@@ -26,6 +26,7 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.android.settingslib.spa.framework.theme.SettingsShape
@@ -35,8 +36,12 @@ import com.android.settingslib.spa.framework.theme.SettingsTheme
internal fun SettingsTab(
title: String,
selected: Boolean,
+ currentPageOffset: Float,
onClick: () -> Unit,
) {
+ // Shows a color transition during pager scroll.
+ // 0f -> Selected, 1f -> Not selected
+ val colorFraction = if (selected) (currentPageOffset * 2).coerceAtMost(1f) else 1f
Tab(
selected = selected,
onClick = onClick,
@@ -44,29 +49,33 @@ internal fun SettingsTab(
.height(48.dp)
.padding(horizontal = 4.dp, vertical = 6.dp)
.clip(SettingsShape.CornerMedium)
- .background(color = when {
- selected -> SettingsTheme.colorScheme.primaryContainer
- else -> SettingsTheme.colorScheme.surface
- }),
+ .background(
+ color = lerp(
+ start = SettingsTheme.colorScheme.primaryContainer,
+ stop = SettingsTheme.colorScheme.surface,
+ fraction = colorFraction,
+ ),
+ ),
) {
Text(
text = title,
style = MaterialTheme.typography.labelLarge,
- color = when {
- selected -> SettingsTheme.colorScheme.onPrimaryContainer
- else -> SettingsTheme.colorScheme.secondaryText
- },
+ color = lerp(
+ start = SettingsTheme.colorScheme.onPrimaryContainer,
+ stop = SettingsTheme.colorScheme.secondaryText,
+ fraction = colorFraction,
+ ),
)
}
}
@Preview
@Composable
-private fun SettingsTabPreview() {
+fun SettingsTabPreview() {
SettingsTheme {
Column {
- SettingsTab(title = "Personal", selected = true) {}
- SettingsTab(title = "Work", selected = false) {}
+ SettingsTab(title = "Personal", selected = true, currentPageOffset = 0f) {}
+ SettingsTab(title = "Work", selected = false, currentPageOffset = 0f) {}
}
}
}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Text.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Text.kt
index a414c89dc24c..59b413cef56e 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Text.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Text.kt
@@ -16,10 +16,14 @@
package com.android.settingslib.spa.widget.ui
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
@Composable
fun SettingsTitle(title: State<String>) {
@@ -50,3 +54,17 @@ fun SettingsBody(body: String) {
)
}
}
+
+@Composable
+fun PlaceholderTitle(title: String) {
+ Box(
+ modifier = Modifier.fillMaxSize(),
+ contentAlignment = Alignment.Center,
+ ) {
+ Text(
+ text = title,
+ color = MaterialTheme.colorScheme.onSurface,
+ style = MaterialTheme.typography.titleLarge,
+ )
+ }
+}
diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsPagerKtTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsPagerKtTest.kt
index f608e1003163..0c84eac45cb7 100644
--- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsPagerKtTest.kt
+++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsPagerKtTest.kt
@@ -18,6 +18,7 @@ package com.android.settingslib.spa.widget.scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.test.assertIsDisplayed
+import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.assertIsNotSelected
import androidx.compose.ui.test.assertIsSelected
import androidx.compose.ui.test.junit4.createComposeRule
@@ -43,7 +44,7 @@ class SettingsPagerKtTest {
composeTestRule.onNodeWithText("Personal").assertIsSelected()
composeTestRule.onNodeWithText("Page 0").assertIsDisplayed()
composeTestRule.onNodeWithText("Work").assertIsNotSelected()
- composeTestRule.onNodeWithText("Page 1").assertDoesNotExist()
+ composeTestRule.onNodeWithText("Page 1").assertIsNotDisplayed()
}
@Test
@@ -55,7 +56,7 @@ class SettingsPagerKtTest {
composeTestRule.onNodeWithText("Work").performClick()
composeTestRule.onNodeWithText("Personal").assertIsNotSelected()
- composeTestRule.onNodeWithText("Page 0").assertDoesNotExist()
+ composeTestRule.onNodeWithText("Page 0").assertIsNotDisplayed()
composeTestRule.onNodeWithText("Work").assertIsSelected()
composeTestRule.onNodeWithText("Page 1").assertIsDisplayed()
}
diff --git a/packages/SettingsLib/SpaPrivileged/Android.bp b/packages/SettingsLib/SpaPrivileged/Android.bp
index ecbb219c64b5..a6469b5172bb 100644
--- a/packages/SettingsLib/SpaPrivileged/Android.bp
+++ b/packages/SettingsLib/SpaPrivileged/Android.bp
@@ -28,5 +28,8 @@ android_library {
"SettingsLib",
"androidx.compose.runtime_runtime",
],
- kotlincflags: ["-Xjvm-default=all"],
+ kotlincflags: [
+ "-Xjvm-default=all",
+ "-Xopt-in=kotlin.RequiresOptIn",
+ ],
}
diff --git a/packages/SettingsLib/SpaPrivileged/res/values/strings.xml b/packages/SettingsLib/SpaPrivileged/res/values/strings.xml
new file mode 100644
index 000000000000..b2302a58229c
--- /dev/null
+++ b/packages/SettingsLib/SpaPrivileged/res/values/strings.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2022 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<resources>
+ <!-- [CHAR LIMIT=25] Text shown when there are no applications to display. -->
+ <string name="no_applications">No apps.</string>
+ <!-- [CHAR LIMIT=NONE] Menu for manage apps to control whether system processes are shown -->
+ <string name="menu_show_system">Show system</string>
+ <!-- [CHAR LIMIT=NONE] Menu for manage apps to control whether system processes are hidden -->
+ <string name="menu_hide_system">Hide system</string>
+ <!-- Preference summary text for an app when it is allowed for a permission. [CHAR LIMIT=45] -->
+ <string name="app_permission_summary_allowed">Allowed</string>
+ <!-- Preference summary text for an app when it is disallowed for a permission. [CHAR LIMIT=45] -->
+ <string name="app_permission_summary_not_allowed">Not allowed</string>
+</resources>
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListModel.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListModel.kt
new file mode 100644
index 000000000000..00eb60b6ec7a
--- /dev/null
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListModel.kt
@@ -0,0 +1,29 @@
+package com.android.settingslib.spaprivileged.model.app
+
+import android.content.pm.ApplicationInfo
+import android.icu.text.CollationKey
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.State
+import kotlinx.coroutines.flow.Flow
+
+data class AppEntry<T : AppRecord>(
+ val record: T,
+ val label: String,
+ val labelCollationKey: CollationKey,
+)
+
+interface AppListModel<T : AppRecord> {
+ fun getSpinnerOptions(): List<String> = emptyList()
+ fun transform(userIdFlow: Flow<Int>, appListFlow: Flow<List<ApplicationInfo>>): Flow<List<T>>
+ fun filter(userIdFlow: Flow<Int>, option: Int, recordListFlow: Flow<List<T>>): Flow<List<T>>
+
+ suspend fun onFirstLoaded(recordList: List<T>) {}
+ fun getComparator(option: Int): Comparator<AppEntry<T>> = compareBy(
+ { it.labelCollationKey },
+ { it.record.app.packageName },
+ { it.record.app.uid },
+ )
+
+ @Composable
+ fun getSummary(option: Int, record: T): State<String>?
+}
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListViewModel.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListViewModel.kt
new file mode 100644
index 000000000000..9265158b3b4a
--- /dev/null
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListViewModel.kt
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spaprivileged.model.app
+
+import android.app.Application
+import android.content.pm.ApplicationInfo
+import android.content.pm.UserInfo
+import android.icu.text.Collator
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.viewModelScope
+import com.android.settingslib.spa.framework.util.StateFlowBridge
+import com.android.settingslib.spa.framework.util.asyncMapItem
+import com.android.settingslib.spa.framework.util.waitFirst
+import java.util.concurrent.ConcurrentHashMap
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.launchIn
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.shareIn
+import kotlinx.coroutines.plus
+
+internal data class AppListData<T : AppRecord>(
+ val appEntries: List<AppEntry<T>>,
+ val option: Int,
+) {
+ fun filter(predicate: (AppEntry<T>) -> Boolean) =
+ AppListData(appEntries.filter(predicate), option)
+}
+
+@OptIn(ExperimentalCoroutinesApi::class)
+internal class AppListViewModel<T : AppRecord>(
+ application: Application,
+) : AndroidViewModel(application) {
+ val userInfo = StateFlowBridge<UserInfo>()
+ val listModel = StateFlowBridge<AppListModel<T>>()
+ val showSystem = StateFlowBridge<Boolean>()
+ val option = StateFlowBridge<Int>()
+ val searchQuery = StateFlowBridge<String>()
+
+ private val appsRepository = AppsRepository(application)
+ private val appRepository = AppRepositoryImpl(application)
+ private val collator = Collator.getInstance().freeze()
+ private val labelMap = ConcurrentHashMap<String, String>()
+ private val scope = viewModelScope + Dispatchers.Default
+
+ private val userIdFlow = userInfo.flow.map { it.id }
+
+ private val recordListFlow = listModel.flow
+ .flatMapLatest { it.transform(userIdFlow, appsRepository.loadApps(userInfo.flow)) }
+ .shareIn(scope = scope, started = SharingStarted.Eagerly, replay = 1)
+
+ private val systemFilteredFlow = appsRepository.showSystemPredicate(userIdFlow, showSystem.flow)
+ .combine(recordListFlow) { showAppPredicate, recordList ->
+ recordList.filter { showAppPredicate(it.app) }
+ }
+
+ val appListDataFlow = option.flow.flatMapLatest(::filterAndSort)
+ .combine(searchQuery.flow) { appListData, searchQuery ->
+ appListData.filter {
+ it.label.contains(other = searchQuery, ignoreCase = true)
+ }
+ }
+ .shareIn(scope = scope, started = SharingStarted.Eagerly, replay = 1)
+
+ init {
+ scheduleOnFirstLoaded()
+ }
+
+ private fun filterAndSort(option: Int) = listModel.flow.flatMapLatest { listModel ->
+ listModel.filter(userIdFlow, option, systemFilteredFlow)
+ .asyncMapItem { record ->
+ val label = getLabel(record.app)
+ AppEntry(
+ record = record,
+ label = label,
+ labelCollationKey = collator.getCollationKey(label),
+ )
+ }
+ .map { appEntries ->
+ AppListData(
+ appEntries = appEntries.sortedWith(listModel.getComparator(option)),
+ option = option,
+ )
+ }
+ }
+
+ private fun scheduleOnFirstLoaded() {
+ recordListFlow
+ .waitFirst(appListDataFlow)
+ .combine(listModel.flow) { recordList, listModel ->
+ listModel.maybePreFetchLabels(recordList)
+ listModel.onFirstLoaded(recordList)
+ }
+ .launchIn(scope)
+ }
+
+ private fun AppListModel<T>.maybePreFetchLabels(recordList: List<T>) {
+ if (getSpinnerOptions().isNotEmpty()) {
+ for (record in recordList) {
+ getLabel(record.app)
+ }
+ }
+ }
+
+ private fun getLabel(app: ApplicationInfo) = labelMap.computeIfAbsent(app.packageName) {
+ appRepository.loadLabel(app)
+ }
+}
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppRepository.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppRepository.kt
index 7ffa9384bfe2..34f12af28dce 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppRepository.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppRepository.kt
@@ -31,6 +31,8 @@ import kotlinx.coroutines.withContext
fun rememberAppRepository(): AppRepository = rememberContext(::AppRepositoryImpl)
interface AppRepository {
+ fun loadLabel(app: ApplicationInfo): String
+
@Composable
fun produceLabel(app: ApplicationInfo): State<String>
@@ -38,9 +40,11 @@ interface AppRepository {
fun produceIcon(app: ApplicationInfo): State<Drawable?>
}
-private class AppRepositoryImpl(private val context: Context) : AppRepository {
+internal class AppRepositoryImpl(private val context: Context) : AppRepository {
private val packageManager = context.packageManager
+ override fun loadLabel(app: ApplicationInfo): String = app.loadLabel(packageManager).toString()
+
@Composable
override fun produceLabel(app: ApplicationInfo) = produceState(initialValue = "", app) {
withContext(Dispatchers.Default) {
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppsRepository.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppsRepository.kt
new file mode 100644
index 000000000000..6a6462098230
--- /dev/null
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppsRepository.kt
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spaprivileged.model.app
+
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ApplicationInfo
+import android.content.pm.PackageManager
+import android.content.pm.ResolveInfo
+import android.content.pm.UserInfo
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.async
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flowOn
+import kotlinx.coroutines.flow.map
+
+class AppsRepository(context: Context) {
+ private val packageManager = context.packageManager
+
+ fun loadApps(userInfoFlow: Flow<UserInfo>): Flow<List<ApplicationInfo>> = userInfoFlow
+ .map { loadApps(it) }
+ .flowOn(Dispatchers.Default)
+
+ private suspend fun loadApps(userInfo: UserInfo): List<ApplicationInfo> {
+ return coroutineScope {
+ val hiddenSystemModulesDeferred = async {
+ packageManager.getInstalledModules(0)
+ .filter { it.isHidden }
+ .map { it.packageName }
+ .toSet()
+ }
+ val flags = PackageManager.ApplicationInfoFlags.of(
+ ((if (userInfo.isAdmin) PackageManager.MATCH_ANY_USER else 0) or
+ PackageManager.MATCH_DISABLED_COMPONENTS or
+ PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS).toLong()
+ )
+ val installedApplicationsAsUser =
+ packageManager.getInstalledApplicationsAsUser(flags, userInfo.id)
+
+ val hiddenSystemModules = hiddenSystemModulesDeferred.await()
+ installedApplicationsAsUser.filter { app ->
+ app.isInAppList(hiddenSystemModules)
+ }
+ }
+ }
+
+ fun showSystemPredicate(
+ userIdFlow: Flow<Int>,
+ showSystemFlow: Flow<Boolean>,
+ ): Flow<(app: ApplicationInfo) -> Boolean> =
+ userIdFlow.combine(showSystemFlow) { userId, showSystem ->
+ showSystemPredicate(userId, showSystem)
+ }
+
+ private suspend fun showSystemPredicate(
+ userId: Int,
+ showSystem: Boolean,
+ ): (app: ApplicationInfo) -> Boolean {
+ if (showSystem) return { true }
+ val homeOrLauncherPackages = loadHomeOrLauncherPackages(userId)
+ return { app ->
+ app.isUpdatedSystemApp || !app.isSystemApp || app.packageName in homeOrLauncherPackages
+ }
+ }
+
+ private suspend fun loadHomeOrLauncherPackages(userId: Int): Set<String> {
+ val launchIntent = Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER)
+ // If we do not specify MATCH_DIRECT_BOOT_AWARE or MATCH_DIRECT_BOOT_UNAWARE, system will
+ // derive and update the flags according to the user's lock state. When the user is locked,
+ // components with ComponentInfo#directBootAware == false will be filtered. We should
+ // explicitly include both direct boot aware and unaware component here.
+ val flags = PackageManager.ResolveInfoFlags.of(
+ (PackageManager.MATCH_DISABLED_COMPONENTS or
+ PackageManager.MATCH_DIRECT_BOOT_AWARE or
+ PackageManager.MATCH_DIRECT_BOOT_UNAWARE).toLong()
+ )
+ return coroutineScope {
+ val launcherActivities = async {
+ packageManager.queryIntentActivitiesAsUser(launchIntent, flags, userId)
+ }
+ val homeActivities = ArrayList<ResolveInfo>()
+ packageManager.getHomeActivities(homeActivities)
+ (launcherActivities.await() + homeActivities)
+ .map { it.activityInfo.packageName }
+ .toSet()
+ }
+ }
+
+ companion object {
+ private fun ApplicationInfo.isInAppList(hiddenSystemModules: Set<String>) =
+ when {
+ packageName in hiddenSystemModules -> false
+ enabled -> true
+ enabledSetting == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER -> true
+ else -> false
+ }
+ }
+}
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfo.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfo.kt
index d802b049b830..99deb707a351 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfo.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfo.kt
@@ -29,8 +29,10 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.android.settingslib.spa.framework.compose.rememberDrawablePainter
+import com.android.settingslib.spa.framework.theme.SettingsDimension
import com.android.settingslib.spa.widget.ui.SettingsBody
import com.android.settingslib.spa.widget.ui.SettingsTitle
import com.android.settingslib.spaprivileged.model.app.PackageManagers
@@ -41,25 +43,35 @@ fun AppInfo(packageName: String, userId: Int) {
Column(
modifier = Modifier
.fillMaxWidth()
- .padding(16.dp),
- horizontalAlignment = Alignment.CenterHorizontally) {
+ .padding(
+ horizontal = SettingsDimension.itemPaddingStart,
+ vertical = SettingsDimension.itemPaddingVertical,
+ ),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
val packageInfo = remember { PackageManagers.getPackageInfoAsUser(packageName, userId) }
- Box(modifier = Modifier.padding(8.dp)) {
- AppIcon(app = packageInfo.applicationInfo, size = 48)
+ Box(modifier = Modifier.padding(SettingsDimension.itemPaddingAround)) {
+ AppIcon(app = packageInfo.applicationInfo, size = SettingsDimension.appIconInfoSize)
}
AppLabel(packageInfo.applicationInfo)
- Spacer(modifier = Modifier.height(4.dp))
- SettingsBody(packageInfo.versionName)
+ AppVersion(packageInfo.versionName)
}
}
@Composable
-fun AppIcon(app: ApplicationInfo, size: Int) {
+private fun AppVersion(versionName: String?) {
+ if (versionName == null) return
+ Spacer(modifier = Modifier.height(4.dp))
+ SettingsBody(versionName)
+}
+
+@Composable
+fun AppIcon(app: ApplicationInfo, size: Dp) {
val appRepository = rememberAppRepository()
Image(
painter = rememberDrawablePainter(appRepository.produceIcon(app).value),
contentDescription = null,
- modifier = Modifier.size(size.dp)
+ modifier = Modifier.size(size)
)
}
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt
index 06d7547be309..9b45318ffd82 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt
@@ -16,15 +16,8 @@
package com.android.settingslib.spaprivileged.template.app
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.rememberScrollState
-import androidx.compose.foundation.verticalScroll
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
-import androidx.compose.ui.Modifier
-import com.android.settingslib.spa.framework.theme.SettingsDimension
+import com.android.settingslib.spa.widget.scaffold.RegularScaffold
import com.android.settingslib.spa.widget.ui.Footer
@Composable
@@ -35,15 +28,7 @@ fun AppInfoPage(
footerText: String,
content: @Composable () -> Unit,
) {
- // TODO: Replace with SettingsScaffold
- Column(Modifier.verticalScroll(rememberScrollState())) {
- Text(
- text = title,
- modifier = Modifier.padding(SettingsDimension.itemPadding),
- color = MaterialTheme.colorScheme.onSurface,
- style = MaterialTheme.typography.headlineMedium,
- )
-
+ RegularScaffold(title = title) {
AppInfo(packageName, userId)
content()
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppList.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppList.kt
new file mode 100644
index 000000000000..315dc5d6ff70
--- /dev/null
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppList.kt
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spaprivileged.template.app
+
+import android.content.pm.UserInfo
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.State
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import androidx.lifecycle.viewmodel.compose.viewModel
+import com.android.settingslib.spa.framework.compose.LogCompositions
+import com.android.settingslib.spa.framework.compose.toState
+import com.android.settingslib.spa.framework.theme.SettingsDimension
+import com.android.settingslib.spa.widget.ui.PlaceholderTitle
+import com.android.settingslib.spaprivileged.R
+import com.android.settingslib.spaprivileged.model.app.AppListData
+import com.android.settingslib.spaprivileged.model.app.AppListModel
+import com.android.settingslib.spaprivileged.model.app.AppListViewModel
+import com.android.settingslib.spaprivileged.model.app.AppRecord
+import kotlinx.coroutines.Dispatchers
+
+private const val TAG = "AppList"
+
+@Composable
+internal fun <T : AppRecord> AppList(
+ userInfo: UserInfo,
+ listModel: AppListModel<T>,
+ showSystem: State<Boolean>,
+ option: State<Int>,
+ searchQuery: State<String>,
+ appItem: @Composable (itemState: AppListItemModel<T>) -> Unit,
+) {
+ LogCompositions(TAG, userInfo.id.toString())
+ val appListData = loadAppEntries(userInfo, listModel, showSystem, option, searchQuery)
+ AppListWidget(appListData, listModel, appItem)
+}
+
+@Composable
+private fun <T : AppRecord> AppListWidget(
+ appListData: State<AppListData<T>?>,
+ listModel: AppListModel<T>,
+ appItem: @Composable (itemState: AppListItemModel<T>) -> Unit,
+) {
+ appListData.value?.let { (list, option) ->
+ if (list.isEmpty()) {
+ PlaceholderTitle(stringResource(R.string.no_applications))
+ return
+ }
+ LazyColumn(
+ modifier = Modifier.fillMaxSize(),
+ state = rememberLazyListState(),
+ contentPadding = PaddingValues(bottom = SettingsDimension.itemPaddingVertical),
+ ) {
+ items(count = list.size, key = { option to list[it].record.app.packageName }) {
+ val appEntry = list[it]
+ val summary = listModel.getSummary(option, appEntry.record) ?: "".toState()
+ val itemModel = remember(appEntry) {
+ AppListItemModel(appEntry.record, appEntry.label, summary)
+ }
+ appItem(itemModel)
+ }
+ }
+ }
+}
+
+@Composable
+private fun <T : AppRecord> loadAppEntries(
+ userInfo: UserInfo,
+ listModel: AppListModel<T>,
+ showSystem: State<Boolean>,
+ option: State<Int>,
+ searchQuery: State<String>,
+): State<AppListData<T>?> {
+ val viewModel: AppListViewModel<T> = viewModel(key = userInfo.id.toString())
+ viewModel.userInfo.setIfAbsent(userInfo)
+ viewModel.listModel.setIfAbsent(listModel)
+ viewModel.showSystem.Sync(showSystem)
+ viewModel.option.Sync(option)
+ viewModel.searchQuery.Sync(searchQuery)
+
+ return viewModel.appListDataFlow.collectAsState(null, Dispatchers.Default)
+}
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListItem.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListItem.kt
new file mode 100644
index 000000000000..ac3f8ff79091
--- /dev/null
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListItem.kt
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spaprivileged.template.app
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.State
+import androidx.compose.runtime.remember
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.tooling.preview.Preview
+import com.android.settingslib.spa.framework.compose.toState
+import com.android.settingslib.spa.framework.theme.SettingsDimension
+import com.android.settingslib.spa.framework.theme.SettingsTheme
+import com.android.settingslib.spa.widget.preference.Preference
+import com.android.settingslib.spa.widget.preference.PreferenceModel
+import com.android.settingslib.spaprivileged.model.app.AppRecord
+
+class AppListItemModel<T : AppRecord>(
+ val record: T,
+ val label: String,
+ val summary: State<String>,
+)
+
+@Composable
+fun <T : AppRecord> AppListItem(
+ itemModel: AppListItemModel<T>,
+ onClick: () -> Unit,
+) {
+ Preference(remember {
+ object : PreferenceModel {
+ override val title = itemModel.label
+ override val summary = itemModel.summary
+ override val icon = @Composable {
+ AppIcon(app = itemModel.record.app, size = SettingsDimension.appIconItemSize)
+ }
+ override val onClick = onClick
+ }
+ })
+}
+
+@Preview
+@Composable
+private fun AppListItemPreview() {
+ SettingsTheme {
+ val record = object : AppRecord {
+ override val app = LocalContext.current.applicationInfo
+ }
+ val itemModel = AppListItemModel<AppRecord>(record, "Chrome", "Allowed".toState())
+ AppListItem(itemModel) {}
+ }
+}
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListPage.kt
new file mode 100644
index 000000000000..dc30e796f64f
--- /dev/null
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListPage.kt
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spaprivileged.template.app
+
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import com.android.settingslib.spa.framework.compose.stateOf
+import com.android.settingslib.spa.widget.scaffold.MoreOptionsAction
+import com.android.settingslib.spa.widget.scaffold.SettingsScaffold
+import com.android.settingslib.spaprivileged.R
+import com.android.settingslib.spaprivileged.model.app.AppListModel
+import com.android.settingslib.spaprivileged.model.app.AppRecord
+import com.android.settingslib.spaprivileged.template.common.WorkProfilePager
+
+@Composable
+fun <T : AppRecord> AppListPage(
+ title: String,
+ listModel: AppListModel<T>,
+ appItem: @Composable (itemState: AppListItemModel<T>) -> Unit,
+) {
+ val showSystem = rememberSaveable { mutableStateOf(false) }
+ // TODO: Use SearchScaffold here.
+ SettingsScaffold(
+ title = title,
+ actions = {
+ ShowSystemAction(showSystem.value) { showSystem.value = it }
+ },
+ ) { paddingValues ->
+ Spacer(Modifier.padding(paddingValues))
+ WorkProfilePager { userInfo ->
+ // TODO: Add a Spinner here.
+ AppList(
+ userInfo = userInfo,
+ listModel = listModel,
+ showSystem = showSystem,
+ option = stateOf(0),
+ searchQuery = stateOf(""),
+ appItem = appItem,
+ )
+ }
+ }
+}
+
+@Composable
+private fun ShowSystemAction(showSystem: Boolean, setShowSystem: (showSystem: Boolean) -> Unit) {
+ var expanded by remember { mutableStateOf(false) }
+ MoreOptionsAction { expanded = true }
+ DropdownMenu(
+ expanded = expanded,
+ onDismissRequest = { expanded = false },
+ ) {
+ val menuText = if (showSystem) R.string.menu_hide_system else R.string.menu_show_system
+ DropdownMenuItem(
+ text = { Text(stringResource(menuText)) },
+ onClick = {
+ expanded = false
+ setShowSystem(!showSystem)
+ },
+ )
+ }
+}
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt
index 430ac5409711..298ecd5106ea 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt
@@ -17,6 +17,7 @@
package com.android.settingslib.spaprivileged.template.app
import android.content.Context
+import android.content.pm.ApplicationInfo
import android.os.Bundle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@@ -28,21 +29,24 @@ import androidx.compose.ui.res.stringResource
import androidx.navigation.NavType
import androidx.navigation.navArgument
import com.android.settingslib.spa.framework.api.SettingsPageProvider
+import com.android.settingslib.spa.framework.compose.navigator
import com.android.settingslib.spa.framework.compose.rememberContext
import com.android.settingslib.spa.widget.preference.SwitchPreference
import com.android.settingslib.spa.widget.preference.SwitchPreferenceModel
import com.android.settingslib.spaprivileged.model.app.AppRecord
import com.android.settingslib.spaprivileged.model.app.PackageManagers
+import com.android.settingslib.spaprivileged.model.app.toRoute
import kotlinx.coroutines.Dispatchers
+private const val NAME = "TogglePermissionAppInfoPage"
private const val PERMISSION = "permission"
private const val PACKAGE_NAME = "packageName"
private const val USER_ID = "userId"
-open class TogglePermissionAppInfoPageProvider(
+internal class TogglePermissionAppInfoPageProvider(
private val factory: TogglePermissionAppListModelFactory,
) : SettingsPageProvider {
- override val name = "TogglePermissionAppInfoPage"
+ override val name = NAME
override val arguments = listOf(
navArgument(PERMISSION) { type = NavType.StringType },
@@ -60,8 +64,11 @@ open class TogglePermissionAppInfoPageProvider(
TogglePermissionAppInfoPage(listModel, packageName, userId)
}
- fun getRoute(permissionType: String, packageName: String, userId: Int): String =
- "$name/$permissionType/$packageName/$userId"
+ companion object {
+ @Composable
+ internal fun navigator(permissionType: String, app: ApplicationInfo) =
+ navigator(route = "$NAME/$permissionType/${app.toRoute()}")
+ }
}
@Composable
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListModel.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListModel.kt
index 3782f7cd301e..70ff9a478af5 100644
--- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListModel.kt
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListModel.kt
@@ -20,14 +20,25 @@ import android.content.Context
import android.content.pm.ApplicationInfo
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
+import androidx.compose.ui.res.stringResource
+import com.android.settingslib.spa.framework.api.SettingsPageProvider
+import com.android.settingslib.spa.framework.compose.rememberContext
+import com.android.settingslib.spa.framework.util.asyncMapItem
+import com.android.settingslib.spa.widget.preference.Preference
+import com.android.settingslib.spa.widget.preference.PreferenceModel
import com.android.settingslib.spaprivileged.model.app.AppRecord
+import kotlinx.coroutines.flow.Flow
interface TogglePermissionAppListModel<T : AppRecord> {
val pageTitleResId: Int
val switchTitleResId: Int
val footerResId: Int
+ fun transform(userIdFlow: Flow<Int>, appListFlow: Flow<List<ApplicationInfo>>): Flow<List<T>> =
+ appListFlow.asyncMapItem(::transformItem)
+
fun transformItem(app: ApplicationInfo): T
+ fun filter(userIdFlow: Flow<Int>, recordListFlow: Flow<List<T>>): Flow<List<T>>
@Composable
fun isAllowed(record: T): State<Boolean?>
@@ -41,4 +52,24 @@ interface TogglePermissionAppListModelFactory {
permission: String,
context: Context,
): TogglePermissionAppListModel<out AppRecord>
+
+ fun createPageProviders(): List<SettingsPageProvider> = listOf(
+ TogglePermissionAppListPageProvider(this),
+ TogglePermissionAppInfoPageProvider(this),
+ )
+
+ @Composable
+ fun EntryItem(permissionType: String) {
+ val listModel = rememberModel(permissionType)
+ Preference(
+ object : PreferenceModel {
+ override val title = stringResource(listModel.pageTitleResId)
+ override val onClick = TogglePermissionAppListPageProvider.navigator(permissionType)
+ }
+ )
+ }
}
+
+@Composable
+internal fun TogglePermissionAppListModelFactory.rememberModel(permission: String) =
+ rememberContext { context -> createModel(permission, context) }
diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListPage.kt
new file mode 100644
index 000000000000..107bf942a2d6
--- /dev/null
+++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListPage.kt
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settingslib.spaprivileged.template.app
+
+import android.content.Context
+import android.content.pm.ApplicationInfo
+import android.os.Bundle
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.State
+import androidx.compose.runtime.derivedStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.navigation.NavType
+import androidx.navigation.navArgument
+import com.android.settingslib.spa.framework.api.SettingsPageProvider
+import com.android.settingslib.spa.framework.compose.navigator
+import com.android.settingslib.spaprivileged.R
+import com.android.settingslib.spaprivileged.model.app.AppListModel
+import com.android.settingslib.spaprivileged.model.app.AppRecord
+import kotlinx.coroutines.flow.Flow
+
+private const val NAME = "TogglePermissionAppList"
+private const val PERMISSION = "permission"
+
+internal class TogglePermissionAppListPageProvider(
+ private val factory: TogglePermissionAppListModelFactory,
+) : SettingsPageProvider {
+ override val name = NAME
+
+ override val arguments = listOf(
+ navArgument(PERMISSION) { type = NavType.StringType },
+ )
+
+ @Composable
+ override fun Page(arguments: Bundle?) {
+ checkNotNull(arguments)
+ val permissionType = checkNotNull(arguments.getString(PERMISSION))
+ TogglePermissionAppList(permissionType)
+ }
+
+ @Composable
+ private fun TogglePermissionAppList(permissionType: String) {
+ val listModel = factory.rememberModel(permissionType)
+ val context = LocalContext.current
+ val internalListModel = remember {
+ TogglePermissionInternalAppListModel(context, listModel)
+ }
+ AppListPage(
+ title = stringResource(listModel.pageTitleResId),
+ listModel = internalListModel,
+ ) { itemModel ->
+ AppListItem(
+ itemModel = itemModel,
+ onClick = TogglePermissionAppInfoPageProvider.navigator(
+ permissionType = permissionType,
+ app = itemModel.record.app,
+ ),
+ )
+ }
+ }
+
+ companion object {
+ @Composable
+ internal fun navigator(permissionType: String) = navigator(route = "$NAME/$permissionType")
+ }
+}
+
+private class TogglePermissionInternalAppListModel<T : AppRecord>(
+ private val context: Context,
+ private val listModel: TogglePermissionAppListModel<T>,
+) : AppListModel<T> {
+ override fun transform(userIdFlow: Flow<Int>, appListFlow: Flow<List<ApplicationInfo>>) =
+ listModel.transform(userIdFlow, appListFlow)
+
+ override fun filter(userIdFlow: Flow<Int>, option: Int, recordListFlow: Flow<List<T>>) =
+ listModel.filter(userIdFlow, recordListFlow)
+
+ @Composable
+ override fun getSummary(option: Int, record: T): State<String> {
+ val allowed = listModel.isAllowed(record)
+ return remember {
+ derivedStateOf {
+ when (allowed.value) {
+ true -> context.getString(R.string.app_permission_summary_allowed)
+ false -> context.getString(R.string.app_permission_summary_not_allowed)
+ else -> ""
+ }
+ }
+ }
+ }
+}
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index aab0d3a08154..06d7bb49c809 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -1601,21 +1601,6 @@
<!-- Content description of the no calling for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
<string name="accessibility_no_calling">No calling.</string>
- <!-- Screensaver overlay which displays the time. [CHAR LIMIT=20] -->
- <string name="dream_complication_title_time">Time</string>
- <!-- Screensaver overlay which displays the date. [CHAR LIMIT=20] -->
- <string name="dream_complication_title_date">Date</string>
- <!-- Screensaver overlay which displays the weather. [CHAR LIMIT=20] -->
- <string name="dream_complication_title_weather">Weather</string>
- <!-- Screensaver overlay which displays air quality. [CHAR LIMIT=20] -->
- <string name="dream_complication_title_aqi">Air Quality</string>
- <!-- Screensaver overlay which displays cast info. [CHAR LIMIT=20] -->
- <string name="dream_complication_title_cast_info">Cast Info</string>
- <!-- Screensaver overlay which displays home controls. [CHAR LIMIT=20] -->
- <string name="dream_complication_title_home_controls">Home Controls</string>
- <!-- Screensaver overlay which displays smartspace. [CHAR LIMIT=20] -->
- <string name="dream_complication_title_smartspace">Smartspace</string>
-
<!-- Title for a screen allowing the user to choose a profile picture. [CHAR LIMIT=NONE] -->
<string name="avatar_picker_title">Choose a profile picture</string>
diff --git a/packages/SettingsLib/src/com/android/settingslib/dream/DreamBackend.java b/packages/SettingsLib/src/com/android/settingslib/dream/DreamBackend.java
index 22586171e5cf..1606540da3fd 100644
--- a/packages/SettingsLib/src/com/android/settingslib/dream/DreamBackend.java
+++ b/packages/SettingsLib/src/com/android/settingslib/dream/DreamBackend.java
@@ -17,7 +17,6 @@
package com.android.settingslib.dream;
import android.annotation.IntDef;
-import android.annotation.Nullable;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -32,17 +31,14 @@ import android.os.ServiceManager;
import android.provider.Settings;
import android.service.dreams.DreamService;
import android.service.dreams.IDreamManager;
-import android.text.TextUtils;
import android.util.Log;
-import com.android.settingslib.R;
-
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Comparator;
-import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@@ -64,18 +60,21 @@ public class DreamBackend {
public String toString() {
StringBuilder sb = new StringBuilder(DreamInfo.class.getSimpleName());
sb.append('[').append(caption);
- if (isActive)
+ if (isActive) {
sb.append(",active");
+ }
sb.append(',').append(componentName);
- if (settingsComponentName != null)
+ if (settingsComponentName != null) {
sb.append("settings=").append(settingsComponentName);
+ }
return sb.append(']').toString();
}
}
@Retention(RetentionPolicy.SOURCE)
@IntDef({WHILE_CHARGING, WHILE_DOCKED, EITHER, NEVER})
- public @interface WhenToDream {}
+ public @interface WhenToDream {
+ }
public static final int WHILE_CHARGING = 0;
public static final int WHILE_DOCKED = 1;
@@ -96,7 +95,8 @@ public class DreamBackend {
COMPLICATION_TYPE_SMARTSPACE
})
@Retention(RetentionPolicy.SOURCE)
- public @interface ComplicationType {}
+ public @interface ComplicationType {
+ }
public static final int COMPLICATION_TYPE_TIME = 1;
public static final int COMPLICATION_TYPE_DATE = 2;
@@ -114,8 +114,6 @@ public class DreamBackend {
private final boolean mDreamsActivatedOnDockByDefault;
private final Set<ComponentName> mDisabledDreams;
private final Set<Integer> mSupportedComplications;
- private final Set<Integer> mDefaultEnabledComplications;
-
private static DreamBackend sInstance;
public static DreamBackend getInstance(Context context) {
@@ -147,13 +145,6 @@ public class DreamBackend {
com.android.internal.R.array.config_supportedDreamComplications))
.boxed()
.collect(Collectors.toSet());
-
- mDefaultEnabledComplications = Arrays.stream(resources.getIntArray(
- com.android.internal.R.array.config_dreamComplicationsEnabledByDefault))
- .boxed()
- // A complication can only be enabled by default if it is also supported.
- .filter(mSupportedComplications::contains)
- .collect(Collectors.toSet());
}
public List<DreamInfo> getDreamInfos() {
@@ -251,11 +242,12 @@ public class DreamBackend {
return null;
}
- public @WhenToDream int getWhenToDreamSetting() {
+ @WhenToDream
+ public int getWhenToDreamSetting() {
return isActivatedOnDock() && isActivatedOnSleep() ? EITHER
: isActivatedOnDock() ? WHILE_DOCKED
- : isActivatedOnSleep() ? WHILE_CHARGING
- : NEVER;
+ : isActivatedOnSleep() ? WHILE_CHARGING
+ : NEVER;
}
public void setWhenToDream(@WhenToDream int whenToDream) {
@@ -283,98 +275,29 @@ public class DreamBackend {
}
}
- /** Returns whether a particular complication is enabled */
- public boolean isComplicationEnabled(@ComplicationType int complication) {
- return getEnabledComplications().contains(complication);
- }
-
/** Gets all complications which have been enabled by the user. */
public Set<Integer> getEnabledComplications() {
- final String enabledComplications = Settings.Secure.getString(
- mContext.getContentResolver(),
- Settings.Secure.SCREENSAVER_ENABLED_COMPLICATIONS);
-
- if (enabledComplications == null) {
- return mDefaultEnabledComplications;
- }
-
- return parseFromString(enabledComplications);
+ return getComplicationsEnabled() ? mSupportedComplications : Collections.emptySet();
}
- /** Gets all dream complications which are supported on this device. **/
- public Set<Integer> getSupportedComplications() {
- return mSupportedComplications;
- }
-
- /**
- * Enables or disables a particular dream complication.
- *
- * @param complicationType The dream complication to be enabled/disabled.
- * @param value If true, the complication is enabled. Otherwise it is disabled.
- */
- public void setComplicationEnabled(@ComplicationType int complicationType, boolean value) {
- if (!mSupportedComplications.contains(complicationType)) return;
-
- Set<Integer> enabledComplications = getEnabledComplications();
- if (value) {
- enabledComplications.add(complicationType);
- } else {
- enabledComplications.remove(complicationType);
- }
-
- Settings.Secure.putString(mContext.getContentResolver(),
- Settings.Secure.SCREENSAVER_ENABLED_COMPLICATIONS,
- convertToString(enabledComplications));
+ /** Sets complication enabled state. */
+ public void setComplicationsEnabled(boolean enabled) {
+ Settings.Secure.putInt(mContext.getContentResolver(),
+ Settings.Secure.SCREENSAVER_COMPLICATIONS_ENABLED, enabled ? 1 : 0);
}
/**
- * Gets the title of a particular complication type to be displayed to the user. If there
- * is no title, null is returned.
+ * Gets whether complications are enabled on this device
*/
- @Nullable
- public CharSequence getComplicationTitle(@ComplicationType int complicationType) {
- int res = 0;
- switch (complicationType) {
- case COMPLICATION_TYPE_TIME:
- res = R.string.dream_complication_title_time;
- break;
- case COMPLICATION_TYPE_DATE:
- res = R.string.dream_complication_title_date;
- break;
- case COMPLICATION_TYPE_WEATHER:
- res = R.string.dream_complication_title_weather;
- break;
- case COMPLICATION_TYPE_AIR_QUALITY:
- res = R.string.dream_complication_title_aqi;
- break;
- case COMPLICATION_TYPE_CAST_INFO:
- res = R.string.dream_complication_title_cast_info;
- break;
- case COMPLICATION_TYPE_HOME_CONTROLS:
- res = R.string.dream_complication_title_home_controls;
- break;
- case COMPLICATION_TYPE_SMARTSPACE:
- res = R.string.dream_complication_title_smartspace;
- break;
- default:
- return null;
- }
- return mContext.getString(res);
- }
-
- private static String convertToString(Set<Integer> set) {
- return set.stream()
- .map(String::valueOf)
- .collect(Collectors.joining(","));
+ public boolean getComplicationsEnabled() {
+ return Settings.Secure.getInt(
+ mContext.getContentResolver(),
+ Settings.Secure.SCREENSAVER_COMPLICATIONS_ENABLED, 1) == 1;
}
- private static Set<Integer> parseFromString(String string) {
- if (TextUtils.isEmpty(string)) {
- return new HashSet<>();
- }
- return Arrays.stream(string.split(","))
- .map(Integer::parseInt)
- .collect(Collectors.toSet());
+ /** Gets all dream complications which are supported on this device. **/
+ public Set<Integer> getSupportedComplications() {
+ return mSupportedComplications;
}
public boolean isEnabled() {
@@ -416,10 +339,11 @@ public class DreamBackend {
public void setActiveDream(ComponentName dream) {
logd("setActiveDream(%s)", dream);
- if (mDreamManager == null)
+ if (mDreamManager == null) {
return;
+ }
try {
- ComponentName[] dreams = { dream };
+ ComponentName[] dreams = {dream};
mDreamManager.setDreamComponents(dream == null ? null : dreams);
} catch (RemoteException e) {
Log.w(TAG, "Failed to set active dream to " + dream, e);
@@ -427,8 +351,9 @@ public class DreamBackend {
}
public ComponentName getActiveDream() {
- if (mDreamManager == null)
+ if (mDreamManager == null) {
return null;
+ }
try {
ComponentName[] dreams = mDreamManager.getDreamComponents();
return dreams != null && dreams.length > 0 ? dreams[0] : null;
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/dream/DreamBackendTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/dream/DreamBackendTest.java
index 86f7850cf1f2..52b9227fb373 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/dream/DreamBackendTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/dream/DreamBackendTest.java
@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
@@ -34,29 +35,35 @@ import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowSettings;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowSettings.ShadowSecure.class})
public final class DreamBackendTest {
private static final int[] SUPPORTED_DREAM_COMPLICATIONS = {1, 2, 3};
- private static final int[] DEFAULT_DREAM_COMPLICATIONS = {1, 3, 4};
+ private static final List<Integer> SUPPORTED_DREAM_COMPLICATIONS_LIST = Arrays.stream(
+ SUPPORTED_DREAM_COMPLICATIONS).boxed().collect(
+ Collectors.toList());
@Mock
private Context mContext;
+ @Mock
+ private ContentResolver mMockResolver;
private DreamBackend mBackend;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(mContext.getApplicationContext()).thenReturn(mContext);
+ when(mContext.getContentResolver()).thenReturn(mMockResolver);
final Resources res = mock(Resources.class);
when(mContext.getResources()).thenReturn(res);
when(res.getIntArray(
com.android.internal.R.array.config_supportedDreamComplications)).thenReturn(
SUPPORTED_DREAM_COMPLICATIONS);
- when(res.getIntArray(
- com.android.internal.R.array.config_dreamComplicationsEnabledByDefault)).thenReturn(
- DEFAULT_DREAM_COMPLICATIONS);
when(res.getStringArray(
com.android.internal.R.array.config_disabledDreamComponents)).thenReturn(
new String[]{});
@@ -69,31 +76,25 @@ public final class DreamBackendTest {
}
@Test
- public void testSupportedComplications() {
- assertThat(mBackend.getSupportedComplications()).containsExactly(1, 2, 3);
- }
-
- @Test
- public void testGetEnabledDreamComplications_default() {
- assertThat(mBackend.getEnabledComplications()).containsExactly(1, 3);
- }
-
- @Test
- public void testEnableComplication() {
- mBackend.setComplicationEnabled(/* complicationType= */ 2, true);
- assertThat(mBackend.getEnabledComplications()).containsExactly(1, 2, 3);
+ public void testComplicationsEnabledByDefault() {
+ assertThat(mBackend.getComplicationsEnabled()).isTrue();
+ assertThat(mBackend.getEnabledComplications()).containsExactlyElementsIn(
+ SUPPORTED_DREAM_COMPLICATIONS_LIST);
}
@Test
- public void testEnableComplication_notSupported() {
- mBackend.setComplicationEnabled(/* complicationType= */ 5, true);
- assertThat(mBackend.getEnabledComplications()).containsExactly(1, 3);
+ public void testEnableComplicationExplicitly() {
+ mBackend.setComplicationsEnabled(true);
+ assertThat(mBackend.getEnabledComplications()).containsExactlyElementsIn(
+ SUPPORTED_DREAM_COMPLICATIONS_LIST);
+ assertThat(mBackend.getComplicationsEnabled()).isTrue();
}
@Test
- public void testDisableComplication() {
- mBackend.setComplicationEnabled(/* complicationType= */ 1, false);
- assertThat(mBackend.getEnabledComplications()).containsExactly(3);
+ public void testDisableComplications() {
+ mBackend.setComplicationsEnabled(false);
+ assertThat(mBackend.getEnabledComplications()).isEmpty();
+ assertThat(mBackend.getComplicationsEnabled()).isFalse();
}
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/MainSwitchBarTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/MainSwitchBarTest.java
index d86bd014988e..24037caf4e6c 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/MainSwitchBarTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/MainSwitchBarTest.java
@@ -16,6 +16,8 @@
package com.android.settingslib.widget;
+import static android.graphics.text.LineBreakConfig.LINE_BREAK_WORD_STYLE_PHRASE;
+
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
@@ -97,4 +99,14 @@ public class MainSwitchBarTest {
assertThat(mBar.getVisibility()).isEqualTo(View.GONE);
}
+
+ @Test
+ public void setTitle_shouldSetCorrectLineBreakStyle() {
+ final String title = "title";
+
+ mBar.setTitle(title);
+ final TextView textView = ((TextView) mBar.findViewById(R.id.switch_text));
+
+ assertThat(textView.getLineBreakWordStyle()).isEqualTo(LINE_BREAK_WORD_STYLE_PHRASE);
+ }
}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/regionsampling/RegionSamplingInstance.kt b/packages/SystemUI/shared/src/com/android/systemui/shared/regionsampling/RegionSamplingInstance.kt
index 0146795f4988..dd2e55d4e7d7 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/regionsampling/RegionSamplingInstance.kt
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/regionsampling/RegionSamplingInstance.kt
@@ -35,6 +35,7 @@ open class RegionSamplingInstance(
) {
private var isDark = RegionDarkness.DEFAULT
private var samplingBounds = Rect()
+ private val tmpScreenLocation = IntArray(2)
@VisibleForTesting var regionSampler: RegionSamplingHelper? = null
/**
@@ -99,10 +100,21 @@ open class RegionSamplingInstance(
isDark = convertToClockDarkness(isRegionDark)
updateFun.updateColors()
}
-
+ /**
+ * The method getLocationOnScreen is used to obtain the view coordinates
+ * relative to its left and top edges on the device screen.
+ * Directly accessing the X and Y coordinates of the view returns the
+ * location relative to its parent view instead.
+ */
override fun getSampledRegion(sampledView: View): Rect {
- samplingBounds = Rect(sampledView.left, sampledView.top,
- sampledView.right, sampledView.bottom)
+ val screenLocation = tmpScreenLocation
+ sampledView.getLocationOnScreen(screenLocation)
+ val left = screenLocation[0]
+ val top = screenLocation[1]
+ samplingBounds.left = left
+ samplingBounds.top = top
+ samplingBounds.right = left + sampledView.width
+ samplingBounds.bottom = top + sampledView.height
return samplingBounds
}
diff --git a/packages/SystemUI/src/com/android/systemui/ActivityIntentHelper.java b/packages/SystemUI/src/com/android/systemui/ActivityIntentHelper.java
index 43b3929808b3..df65bcf9c10d 100644
--- a/packages/SystemUI/src/com/android/systemui/ActivityIntentHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/ActivityIntentHelper.java
@@ -16,6 +16,7 @@
package com.android.systemui;
+import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
@@ -34,12 +35,12 @@ import javax.inject.Inject;
@SysUISingleton
public class ActivityIntentHelper {
- private final Context mContext;
+ private final PackageManager mPm;
@Inject
public ActivityIntentHelper(Context context) {
// TODO: inject a package manager, not a context.
- mContext = context;
+ mPm = context.getPackageManager();
}
/**
@@ -57,6 +58,15 @@ public class ActivityIntentHelper {
}
/**
+ * @see #wouldLaunchResolverActivity(Intent, int)
+ */
+ public boolean wouldPendingLaunchResolverActivity(PendingIntent intent, int currentUserId) {
+ ActivityInfo targetActivityInfo = getPendingTargetActivityInfo(intent, currentUserId,
+ false /* onlyDirectBootAware */);
+ return targetActivityInfo == null;
+ }
+
+ /**
* Returns info about the target Activity of a given intent, or null if the intent does not
* resolve to a specific component meeting the requirements.
*
@@ -68,19 +78,45 @@ public class ActivityIntentHelper {
*/
public ActivityInfo getTargetActivityInfo(Intent intent, int currentUserId,
boolean onlyDirectBootAware) {
- PackageManager packageManager = mContext.getPackageManager();
- int flags = PackageManager.MATCH_DEFAULT_ONLY;
+ int flags = PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA;
if (!onlyDirectBootAware) {
flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE
| PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
}
- final List<ResolveInfo> appList = packageManager.queryIntentActivitiesAsUser(
+ final List<ResolveInfo> appList = mPm.queryIntentActivitiesAsUser(
intent, flags, currentUserId);
if (appList.size() == 0) {
return null;
}
- ResolveInfo resolved = packageManager.resolveActivityAsUser(intent,
- flags | PackageManager.GET_META_DATA, currentUserId);
+ if (appList.size() == 1) {
+ return appList.get(0).activityInfo;
+ }
+ ResolveInfo resolved = mPm.resolveActivityAsUser(intent, flags, currentUserId);
+ if (resolved == null || wouldLaunchResolverActivity(resolved, appList)) {
+ return null;
+ } else {
+ return resolved.activityInfo;
+ }
+ }
+
+ /**
+ * @see #getTargetActivityInfo(Intent, int, boolean)
+ */
+ public ActivityInfo getPendingTargetActivityInfo(PendingIntent intent, int currentUserId,
+ boolean onlyDirectBootAware) {
+ int flags = PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA;
+ if (!onlyDirectBootAware) {
+ flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE
+ | PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
+ }
+ final List<ResolveInfo> appList = intent.queryIntentComponents(flags);
+ if (appList.size() == 0) {
+ return null;
+ }
+ if (appList.size() == 1) {
+ return appList.get(0).activityInfo;
+ }
+ ResolveInfo resolved = mPm.resolveActivityAsUser(intent.getIntent(), flags, currentUserId);
if (resolved == null || wouldLaunchResolverActivity(resolved, appList)) {
return null;
} else {
@@ -104,6 +140,17 @@ public class ActivityIntentHelper {
}
/**
+ * @see #wouldShowOverLockscreen(Intent, int)
+ */
+ public boolean wouldPendingShowOverLockscreen(PendingIntent intent, int currentUserId) {
+ ActivityInfo targetActivityInfo = getPendingTargetActivityInfo(intent,
+ currentUserId, false /* onlyDirectBootAware */);
+ return targetActivityInfo != null
+ && (targetActivityInfo.flags & (ActivityInfo.FLAG_SHOW_WHEN_LOCKED
+ | ActivityInfo.FLAG_SHOW_FOR_ALL_USERS)) > 0;
+ }
+
+ /**
* Determines if sending the given intent would result in starting an Intent resolver activity,
* instead of resolving to a specific component.
*
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/complication/ComplicationTypesUpdater.java b/packages/SystemUI/src/com/android/systemui/dreams/complication/ComplicationTypesUpdater.java
index 83249aa324d1..bbcab60d7ba2 100644
--- a/packages/SystemUI/src/com/android/systemui/dreams/complication/ComplicationTypesUpdater.java
+++ b/packages/SystemUI/src/com/android/systemui/dreams/complication/ComplicationTypesUpdater.java
@@ -69,7 +69,7 @@ public class ComplicationTypesUpdater extends CoreStartable {
};
mSecureSettings.registerContentObserverForUser(
- Settings.Secure.SCREENSAVER_ENABLED_COMPLICATIONS,
+ Settings.Secure.SCREENSAVER_COMPLICATIONS_ENABLED,
settingsObserver,
UserHandle.myUserId());
settingsObserver.onChange(false);
diff --git a/packages/SystemUI/src/com/android/systemui/flags/Flags.java b/packages/SystemUI/src/com/android/systemui/flags/Flags.java
index 677f0a2e288b..29d67650fbd8 100644
--- a/packages/SystemUI/src/com/android/systemui/flags/Flags.java
+++ b/packages/SystemUI/src/com/android/systemui/flags/Flags.java
@@ -155,10 +155,10 @@ public class Flags {
new ReleasedFlag(603, false);
public static final UnreleasedFlag NEW_STATUS_BAR_PIPELINE_BACKEND =
- new UnreleasedFlag(604, true);
+ new UnreleasedFlag(604, false);
public static final UnreleasedFlag NEW_STATUS_BAR_PIPELINE_FRONTEND =
- new UnreleasedFlag(605, true);
+ new UnreleasedFlag(605, false);
/***************************************/
// 700 - dialer/calls
diff --git a/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/EdgeBackGestureHandler.java b/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/EdgeBackGestureHandler.java
index 6ac3eadb838d..7c4c64c20089 100644
--- a/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/EdgeBackGestureHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/EdgeBackGestureHandler.java
@@ -814,8 +814,10 @@ public class EdgeBackGestureHandler extends CurrentUserTracker
}
mLogGesture = false;
String logPackageName = "";
+ Map<String, Integer> vocab = mVocab;
// Due to privacy, only top 100 most used apps by all users can be logged.
- if (mUseMLModel && mVocab.containsKey(mPackageName) && mVocab.get(mPackageName) < 100) {
+ if (mUseMLModel && vocab != null && vocab.containsKey(mPackageName)
+ && vocab.get(mPackageName) < 100) {
logPackageName = mPackageName;
}
SysUiStatsLog.write(SysUiStatsLog.BACK_GESTURE_REPORTED_REPORTED, backType,
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
index 8b37aab87665..35f32caffe21 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
@@ -53,8 +53,7 @@ import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
-import androidx.annotation.NonNull;
-
+import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.UiEventLogger;
import com.android.internal.util.ScreenshotHelper;
import com.android.systemui.R;
@@ -137,7 +136,7 @@ public class TakeScreenshotService extends Service {
}
@Override
- public IBinder onBind(@NonNull Intent intent) {
+ public IBinder onBind(Intent intent) {
registerReceiver(mCloseSystemDialogs, new IntentFilter(ACTION_CLOSE_SYSTEM_DIALOGS),
Context.RECEIVER_EXPORTED);
final Messenger m = new Messenger(mHandler);
@@ -184,13 +183,23 @@ public class TakeScreenshotService extends Service {
}
}
- /** Respond to incoming Message via Binder (Messenger) */
@MainThread
private boolean handleMessage(Message msg) {
final Messenger replyTo = msg.replyTo;
- final Consumer<Uri> uriConsumer = (uri) -> reportUri(replyTo, uri);
- RequestCallback requestCallback = new RequestCallbackImpl(replyTo);
+ final Consumer<Uri> onSaved = (uri) -> reportUri(replyTo, uri);
+ RequestCallback callback = new RequestCallbackImpl(replyTo);
+
+ ScreenshotHelper.ScreenshotRequest request =
+ (ScreenshotHelper.ScreenshotRequest) msg.obj;
+ handleRequest(request, onSaved, callback);
+ return true;
+ }
+
+ @MainThread
+ @VisibleForTesting
+ void handleRequest(ScreenshotHelper.ScreenshotRequest request, Consumer<Uri> onSaved,
+ RequestCallback callback) {
// If the storage for this user is locked, we have no place to store
// the screenshot, so skip taking it instead of showing a misleading
// animation and error notification.
@@ -198,8 +207,8 @@ public class TakeScreenshotService extends Service {
Log.w(TAG, "Skipping screenshot because storage is locked!");
mNotificationsController.notifyScreenshotError(
R.string.screenshot_failed_to_save_user_locked_text);
- requestCallback.reportError();
- return true;
+ callback.reportError();
+ return;
}
if (mDevicePolicyManager.getScreenCaptureDisabled(null, UserHandle.USER_ALL)) {
@@ -211,33 +220,26 @@ public class TakeScreenshotService extends Service {
() -> mContext.getString(R.string.screenshot_blocked_by_admin));
mHandler.post(() ->
Toast.makeText(mContext, blockedByAdminText, Toast.LENGTH_SHORT).show());
- requestCallback.reportError();
+ callback.reportError();
});
- return true;
+ return;
}
- ScreenshotHelper.ScreenshotRequest screenshotRequest =
- (ScreenshotHelper.ScreenshotRequest) msg.obj;
-
- ComponentName topComponent = screenshotRequest.getTopComponent();
- mUiEventLogger.log(ScreenshotEvent.getScreenshotSource(screenshotRequest.getSource()), 0,
- topComponent == null ? "" : topComponent.getPackageName());
-
if (mFeatureFlags.isEnabled(SCREENSHOT_REQUEST_PROCESSOR)) {
Log.d(TAG, "handleMessage: Using request processor");
- mProcessor.processAsync(screenshotRequest,
- (request) -> dispatchToController(request, uriConsumer, requestCallback));
- return true;
+ mProcessor.processAsync(request,
+ (r) -> dispatchToController(r, onSaved, callback));
}
- dispatchToController(screenshotRequest, uriConsumer, requestCallback);
- return true;
+ dispatchToController(request, onSaved, callback);
}
private void dispatchToController(ScreenshotHelper.ScreenshotRequest request,
Consumer<Uri> uriConsumer, RequestCallback callback) {
ComponentName topComponent = request.getTopComponent();
+ mUiEventLogger.log(ScreenshotEvent.getScreenshotSource(request.getSource()), 0,
+ topComponent == null ? "" : topComponent.getPackageName());
switch (request.getType()) {
case WindowManager.TAKE_SCREENSHOT_FULLSCREEN:
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
index 7a4c87766114..29c7633ca93e 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java
@@ -54,7 +54,6 @@ import android.graphics.ColorFilter;
import android.graphics.Insets;
import android.graphics.Paint;
import android.graphics.PixelFormat;
-import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
@@ -98,6 +97,7 @@ import com.android.internal.policy.ScreenDecorationsUtils;
import com.android.internal.policy.SystemBarUtils;
import com.android.internal.util.LatencyTracker;
import com.android.keyguard.ActiveUnlockConfig;
+import com.android.keyguard.KeyguardClockSwitch.ClockSize;
import com.android.keyguard.KeyguardStatusView;
import com.android.keyguard.KeyguardStatusViewController;
import com.android.keyguard.KeyguardUnfoldTransition;
@@ -1416,19 +1416,10 @@ public final class NotificationPanelViewController extends PanelViewController {
private void updateClockAppearance() {
int userSwitcherPreferredY = mStatusBarHeaderHeightKeyguard;
boolean bypassEnabled = mKeyguardBypassController.getBypassEnabled();
- final boolean hasVisibleNotifications = mNotificationStackScrollLayoutController
- .getVisibleNotificationCount() != 0
- || mMediaDataManager.hasActiveMediaOrRecommendation();
- boolean splitShadeWithActiveMedia =
- mSplitShadeEnabled && mMediaDataManager.hasActiveMediaOrRecommendation();
boolean shouldAnimateClockChange = mScreenOffAnimationController.shouldAnimateClockChange();
- if ((hasVisibleNotifications && !mSplitShadeEnabled)
- || (splitShadeWithActiveMedia && !mDozing)) {
- mKeyguardStatusViewController.displayClock(SMALL, shouldAnimateClockChange);
- } else {
- mKeyguardStatusViewController.displayClock(LARGE, shouldAnimateClockChange);
- }
- updateKeyguardStatusViewAlignment(true /* animate */);
+ mKeyguardStatusViewController.displayClock(computeDesiredClockSize(),
+ shouldAnimateClockChange);
+ updateKeyguardStatusViewAlignment(/* animate= */true);
int userSwitcherHeight = mKeyguardQsUserSwitchController != null
? mKeyguardQsUserSwitchController.getUserIconHeight() : 0;
if (mKeyguardUserSwitcherController != null) {
@@ -1437,7 +1428,7 @@ public final class NotificationPanelViewController extends PanelViewController {
float expandedFraction =
mScreenOffAnimationController.shouldExpandNotifications()
? 1.0f : getExpandedFraction();
- float darkamount =
+ float darkAmount =
mScreenOffAnimationController.shouldExpandNotifications()
? 1.0f : mInterpolatedDarkAmount;
@@ -1455,7 +1446,7 @@ public final class NotificationPanelViewController extends PanelViewController {
mKeyguardStatusViewController.getLockscreenHeight(),
userSwitcherHeight,
userSwitcherPreferredY,
- darkamount, mOverStretchAmount,
+ darkAmount, mOverStretchAmount,
bypassEnabled, getUnlockedStackScrollerPadding(),
computeQsExpansionFraction(),
mDisplayTopInset,
@@ -1487,6 +1478,34 @@ public final class NotificationPanelViewController extends PanelViewController {
updateClock();
}
+ @ClockSize
+ private int computeDesiredClockSize() {
+ if (mSplitShadeEnabled) {
+ return computeDesiredClockSizeForSplitShade();
+ }
+ return computeDesiredClockSizeForSingleShade();
+ }
+
+ @ClockSize
+ private int computeDesiredClockSizeForSingleShade() {
+ if (hasVisibleNotifications()) {
+ return SMALL;
+ }
+ return LARGE;
+ }
+
+ @ClockSize
+ private int computeDesiredClockSizeForSplitShade() {
+ // Media is not visible to the user on AOD.
+ boolean isMediaVisibleToUser =
+ mMediaDataManager.hasActiveMediaOrRecommendation() && !isOnAod();
+ if (isMediaVisibleToUser) {
+ // When media is visible, it overlaps with the large clock. Use small clock instead.
+ return SMALL;
+ }
+ return LARGE;
+ }
+
private void updateKeyguardStatusViewAlignment(boolean animate) {
boolean shouldBeCentered = shouldKeyguardStatusViewBeCentered();
if (mStatusViewCentered != shouldBeCentered) {
@@ -1513,12 +1532,35 @@ public final class NotificationPanelViewController extends PanelViewController {
}
private boolean shouldKeyguardStatusViewBeCentered() {
- boolean hasVisibleNotifications = mNotificationStackScrollLayoutController
+ if (mSplitShadeEnabled) {
+ return shouldKeyguardStatusViewBeCenteredInSplitShade();
+ }
+ return true;
+ }
+
+ private boolean shouldKeyguardStatusViewBeCenteredInSplitShade() {
+ if (!hasVisibleNotifications()) {
+ // No notifications visible. It is safe to have the clock centered as there will be no
+ // overlap.
+ return true;
+ }
+ if (hasPulsingNotifications()) {
+ // Pulsing notification appears on the right. Move clock left to avoid overlap.
+ return false;
+ }
+ // "Visible" notifications are actually not visible on AOD (unless pulsing), so it is safe
+ // to center the clock without overlap.
+ return isOnAod();
+ }
+
+ private boolean isOnAod() {
+ return mDozing && mDozeParameters.getAlwaysOn();
+ }
+
+ private boolean hasVisibleNotifications() {
+ return mNotificationStackScrollLayoutController
.getVisibleNotificationCount() != 0
|| mMediaDataManager.hasActiveMediaOrRecommendation();
- boolean isOnAod = mDozing && mDozeParameters.getAlwaysOn();
- return !mSplitShadeEnabled || !hasVisibleNotifications || isOnAod
- || hasPulsingNotifications();
}
/**
@@ -3752,13 +3794,12 @@ public final class NotificationPanelViewController extends PanelViewController {
*
* @param dozing {@code true} when dozing.
* @param animate if transition should be animated.
- * @param wakeUpTouchLocation touch event location - if woken up by SLPI sensor.
*/
- public void setDozing(boolean dozing, boolean animate, PointF wakeUpTouchLocation) {
+ public void setDozing(boolean dozing, boolean animate) {
if (dozing == mDozing) return;
mView.setDozing(dozing);
mDozing = dozing;
- mNotificationStackScrollLayoutController.setDozing(mDozing, animate, wakeUpTouchLocation);
+ mNotificationStackScrollLayoutController.setDozing(mDozing, animate);
mKeyguardBottomArea.setDozing(mDozing, animate);
mKeyguardBottomAreaInteractorProvider.get().setAnimateDozingTransitions(animate);
mKeyguardStatusBarViewController.setDozing(mDozing);
@@ -3791,6 +3832,8 @@ public final class NotificationPanelViewController extends PanelViewController {
mAnimateNextPositionUpdate = false;
}
mNotificationStackScrollLayoutController.setPulsing(pulsing, animatePulse);
+
+ updateKeyguardStatusViewAlignment(/* animate= */ true);
}
public void setAmbientIndicationTop(int ambientIndicationTop, boolean ambientTextVisible) {
@@ -4683,7 +4726,7 @@ public final class NotificationPanelViewController extends PanelViewController {
* change.
*/
public void showAodUi() {
- setDozing(true /* dozing */, false /* animate */, null);
+ setDozing(true /* dozing */, false /* animate */);
mStatusBarStateController.setUpcomingState(KEYGUARD);
mEntryManager.updateNotifications("showAodUi");
mStatusBarStateListener.onStateChanged(KEYGUARD);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java
index 0280e0b729a9..c04bc8289f81 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java
@@ -303,11 +303,6 @@ public class StatusBarStateControllerImpl implements
}
@Override
- public void setDozeAmount(float dozeAmount, boolean animated) {
- setAndInstrumentDozeAmount(null, dozeAmount, animated);
- }
-
- @Override
public void setAndInstrumentDozeAmount(View view, float dozeAmount, boolean animated) {
if (mDarkAnimator != null && mDarkAnimator.isRunning()) {
if (animated && mDozeAmountTarget == dozeAmount) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/SysuiStatusBarStateController.java b/packages/SystemUI/src/com/android/systemui/statusbar/SysuiStatusBarStateController.java
index 2b3190159ecd..2cc77384fb2a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/SysuiStatusBarStateController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/SysuiStatusBarStateController.java
@@ -99,14 +99,6 @@ public interface SysuiStatusBarStateController extends StatusBarStateController
boolean setIsDozing(boolean isDozing);
/**
- * Changes the current doze amount.
- *
- * @param dozeAmount New doze/dark amount.
- * @param animated If change should be animated or not. This will cancel current animations.
- */
- void setDozeAmount(float dozeAmount, boolean animated);
-
- /**
* Changes the current doze amount, also starts the
* {@link com.android.internal.jank.InteractionJankMonitor InteractionJankMonitor} as possible.
*
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListAttachState.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListAttachState.kt
index 9e5dab1152ec..f8449ae8807b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListAttachState.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListAttachState.kt
@@ -90,6 +90,18 @@ data class ListAttachState private constructor(
stableIndex = -1
}
+ /**
+ * Erases bookkeeping traces stored on an entry when it is removed from the notif list.
+ * This can happen if the entry is removed from a group that was broken up or if the entry was
+ * filtered out during any of the filtering steps.
+ */
+ fun detach() {
+ parent = null
+ section = null
+ promoter = null
+ // stableIndex = -1 // TODO(b/241229236): Clear this once we fix the stability fragility
+ }
+
companion object {
@JvmStatic
fun create(): ListAttachState {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java
index 14cc6bf1ea41..3eaa988e8389 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java
@@ -958,9 +958,7 @@ public class ShadeListBuilder implements Dumpable, PipelineDumpable {
* filtered out during any of the filtering steps.
*/
private void annulAddition(ListEntry entry) {
- entry.setParent(null);
- entry.getAttachState().setSection(null);
- entry.getAttachState().setPromoter(null);
+ entry.getAttachState().detach();
}
private void assignSections() {
@@ -1198,9 +1196,9 @@ public class ShadeListBuilder implements Dumpable, PipelineDumpable {
o2.getSectionIndex());
if (cmp != 0) return cmp;
- int index1 = canReorder(o1) ? -1 : o1.getPreviousAttachState().getStableIndex();
- int index2 = canReorder(o2) ? -1 : o2.getPreviousAttachState().getStableIndex();
- cmp = Integer.compare(index1, index2);
+ cmp = Integer.compare(
+ getStableOrderIndex(o1),
+ getStableOrderIndex(o2));
if (cmp != 0) return cmp;
NotifComparator sectionComparator = getSectionComparator(o1, o2);
@@ -1214,31 +1212,32 @@ public class ShadeListBuilder implements Dumpable, PipelineDumpable {
if (cmp != 0) return cmp;
}
- final NotificationEntry rep1 = o1.getRepresentativeEntry();
- final NotificationEntry rep2 = o2.getRepresentativeEntry();
- cmp = rep1.getRanking().getRank() - rep2.getRanking().getRank();
+ cmp = Integer.compare(
+ o1.getRepresentativeEntry().getRanking().getRank(),
+ o2.getRepresentativeEntry().getRanking().getRank());
if (cmp != 0) return cmp;
- cmp = Long.compare(
- rep2.getSbn().getNotification().when,
- rep1.getSbn().getNotification().when);
+ cmp = -1 * Long.compare(
+ o1.getRepresentativeEntry().getSbn().getNotification().when,
+ o2.getRepresentativeEntry().getSbn().getNotification().when);
return cmp;
};
private final Comparator<NotificationEntry> mGroupChildrenComparator = (o1, o2) -> {
- int index1 = canReorder(o1) ? -1 : o1.getPreviousAttachState().getStableIndex();
- int index2 = canReorder(o2) ? -1 : o2.getPreviousAttachState().getStableIndex();
- int cmp = Integer.compare(index1, index2);
+ int cmp = Integer.compare(
+ getStableOrderIndex(o1),
+ getStableOrderIndex(o2));
if (cmp != 0) return cmp;
- cmp = o1.getRepresentativeEntry().getRanking().getRank()
- - o2.getRepresentativeEntry().getRanking().getRank();
+ cmp = Integer.compare(
+ o1.getRepresentativeEntry().getRanking().getRank(),
+ o2.getRepresentativeEntry().getRanking().getRank());
if (cmp != 0) return cmp;
- cmp = Long.compare(
- o2.getRepresentativeEntry().getSbn().getNotification().when,
- o1.getRepresentativeEntry().getSbn().getNotification().when);
+ cmp = -1 * Long.compare(
+ o1.getRepresentativeEntry().getSbn().getNotification().when,
+ o2.getRepresentativeEntry().getSbn().getNotification().when);
return cmp;
};
@@ -1248,8 +1247,16 @@ public class ShadeListBuilder implements Dumpable, PipelineDumpable {
*/
private boolean mForceReorderable = false;
- private boolean canReorder(ListEntry entry) {
- return mForceReorderable || getStabilityManager().isEntryReorderingAllowed(entry);
+ private int getStableOrderIndex(ListEntry entry) {
+ if (mForceReorderable) {
+ // this is used to determine if the list is correctly sorted
+ return -1;
+ }
+ if (getStabilityManager().isEntryReorderingAllowed(entry)) {
+ // let the stability manager constrain or allow reordering
+ return -1;
+ }
+ return entry.getPreviousAttachState().getStableIndex();
}
private boolean applyFilters(NotificationEntry entry, long now, List<NotifFilter> filters) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
index 9ad906c83e10..855390d75ff8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
@@ -20,7 +20,6 @@ import static android.app.Notification.Action.SEMANTIC_ACTION_MARK_CONVERSATION_
import static android.service.notification.NotificationListenerService.REASON_CANCEL;
import static com.android.systemui.statusbar.notification.row.NotificationContentView.VISIBLE_TYPE_HEADSUP;
-import static com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.FLAG_CONTENT_VIEW_PUBLIC;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -236,11 +235,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
*/
private boolean mIsHeadsUp;
- /**
- * Whether or not the notification should be redacted on the lock screen, i.e has sensitive
- * content which should be redacted on the lock screen.
- */
- private boolean mNeedsRedaction;
private boolean mLastChronometerRunning = true;
private ViewStub mChildrenContainerStub;
private GroupMembershipManager mGroupMembershipManager;
@@ -1502,23 +1496,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
mUseIncreasedHeadsUpHeight = use;
}
- /** @deprecated TODO: Remove this when the old pipeline code is removed. */
- @Deprecated
- public void setNeedsRedaction(boolean needsRedaction) {
- if (mNeedsRedaction != needsRedaction) {
- mNeedsRedaction = needsRedaction;
- if (!isRemoved()) {
- RowContentBindParams params = mRowContentBindStage.getStageParams(mEntry);
- if (needsRedaction) {
- params.requireContentViews(FLAG_CONTENT_VIEW_PUBLIC);
- } else {
- params.markContentViewsFreeable(FLAG_CONTENT_VIEW_PUBLIC);
- }
- mRowContentBindStage.requestRebind(mEntry, null /* callback */);
- }
- }
- }
-
public interface ExpansionLogger {
void logNotificationExpansion(String key, boolean userAction, boolean expanded);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
index 952bafbe6eb3..79d883b32a98 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
@@ -42,7 +42,6 @@ import android.graphics.Color;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.Path;
-import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Bundle;
import android.provider.Settings;
@@ -4405,8 +4404,7 @@ public class NotificationStackScrollLayout extends ViewGroup implements Dumpable
* See {@link AmbientState#setDozing}.
*/
@ShadeViewRefactor(RefactorComponent.SHADE_VIEW)
- public void setDozing(boolean dozing, boolean animate,
- @Nullable PointF touchWakeUpScreenLocation) {
+ public void setDozing(boolean dozing, boolean animate) {
if (mAmbientState.isDozing() == dozing) {
return;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
index 9998fe41b775..3f6586c37b5d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
@@ -33,7 +33,6 @@ import static com.android.systemui.statusbar.phone.NotificationIconAreaControlle
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Point;
-import android.graphics.PointF;
import android.os.Trace;
import android.os.UserHandle;
import android.provider.Settings;
@@ -1235,8 +1234,8 @@ public class NotificationStackScrollLayoutController {
mView.setAnimationsEnabled(enabled);
}
- public void setDozing(boolean dozing, boolean animate, PointF wakeUpTouchLocation) {
- mView.setDozing(dozing, animate, wakeUpTouchLocation);
+ public void setDozing(boolean dozing, boolean animate) {
+ mView.setDozing(dozing, animate);
}
public void setPulsing(boolean pulsing, boolean animatePulse) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
index b0a5adb62339..e444e0a1e2c5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java
@@ -67,7 +67,6 @@ import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Point;
-import android.graphics.PointF;
import android.hardware.devicestate.DeviceStateManager;
import android.metrics.LogMaker;
import android.net.Uri;
@@ -446,7 +445,6 @@ public class CentralSurfacesImpl extends CoreStartable implements
@VisibleForTesting
DozeServiceHost mDozeServiceHost;
private boolean mWakeUpComingFromTouch;
- private PointF mWakeUpTouchLocation;
private LightRevealScrim mLightRevealScrim;
private PowerButtonReveal mPowerButtonReveal;
@@ -603,8 +601,6 @@ public class CentralSurfacesImpl extends CoreStartable implements
private int mLastCameraLaunchSource;
protected PowerManager.WakeLock mGestureWakeLock;
- private final int[] mTmpInt2 = new int[2];
-
// Fingerprint (as computed by getLoggingFingerprint() of the last logged state.
private int mLastLoggedStateFingerprint;
private boolean mIsLaunchingActivityOverLockscreen;
@@ -1430,16 +1426,6 @@ public class CentralSurfacesImpl extends CoreStartable implements
mPowerManager.wakeUp(
time, PowerManager.WAKE_REASON_GESTURE, "com.android.systemui:" + why);
mWakeUpComingFromTouch = true;
-
- // NOTE, the incoming view can sometimes be the entire container... unsure if
- // this location is valuable enough
- if (where != null) {
- where.getLocationInWindow(mTmpInt2);
- mWakeUpTouchLocation = new PointF(mTmpInt2[0] + where.getWidth() / 2,
- mTmpInt2[1] + where.getHeight() / 2);
- } else {
- mWakeUpTouchLocation = new PointF(-1, -1);
- }
mFalsingCollector.onScreenOnFromTouch();
}
}
@@ -1955,7 +1941,6 @@ public class CentralSurfacesImpl extends CoreStartable implements
PowerManager.WAKE_REASON_APPLICATION,
"com.android.systemui:full_screen_intent");
mWakeUpComingFromTouch = false;
- mWakeUpTouchLocation = null;
}
}
@@ -3225,7 +3210,7 @@ public class CentralSurfacesImpl extends CoreStartable implements
|| (mDozing && mDozeParameters.shouldControlScreenOff()
&& visibleNotOccludedOrWillBe);
- mNotificationPanelViewController.setDozing(mDozing, animate, mWakeUpTouchLocation);
+ mNotificationPanelViewController.setDozing(mDozing, animate);
updateQsExpansionEnabled();
Trace.endSection();
}
@@ -3556,7 +3541,6 @@ public class CentralSurfacesImpl extends CoreStartable implements
mLaunchCameraWhenFinishedWaking = false;
mDeviceInteractive = false;
mWakeUpComingFromTouch = false;
- mWakeUpTouchLocation = null;
updateVisibleToUser();
updateNotificationPanelTouchState();
@@ -4065,7 +4049,7 @@ public class CentralSurfacesImpl extends CoreStartable implements
final PendingIntent intent, @Nullable final Runnable intentSentUiThreadCallback,
@Nullable ActivityLaunchAnimator.Controller animationController) {
final boolean willLaunchResolverActivity = intent.isActivity()
- && mActivityIntentHelper.wouldLaunchResolverActivity(intent.getIntent(),
+ && mActivityIntentHelper.wouldPendingLaunchResolverActivity(intent,
mLockscreenUserManager.getCurrentUserId());
boolean animate = !willLaunchResolverActivity
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
index 374f0916fb33..5cd2ba1b1cf3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
@@ -223,12 +223,12 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte
boolean isActivityIntent = intent != null && intent.isActivity() && !isBubble;
final boolean willLaunchResolverActivity = isActivityIntent
- && mActivityIntentHelper.wouldLaunchResolverActivity(intent.getIntent(),
+ && mActivityIntentHelper.wouldPendingLaunchResolverActivity(intent,
mLockscreenUserManager.getCurrentUserId());
final boolean animate = !willLaunchResolverActivity
&& mCentralSurfaces.shouldAnimateLaunch(isActivityIntent);
boolean showOverLockscreen = mKeyguardStateController.isShowing() && intent != null
- && mActivityIntentHelper.wouldShowOverLockscreen(intent.getIntent(),
+ && mActivityIntentHelper.wouldPendingShowOverLockscreen(intent,
mLockscreenUserManager.getCurrentUserId());
ActivityStarter.OnDismissAction postKeyguardAction = new ActivityStarter.OnDismissAction() {
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
index 40b9a152057a..70af77e1eb36 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
@@ -259,8 +259,9 @@ public class StatusBarRemoteInputCallback implements Callback, Callbacks,
final boolean isActivity = pendingIntent.isActivity();
if (isActivity || appRequestedAuth) {
mActionClickLogger.logWaitingToCloseKeyguard(pendingIntent);
- final boolean afterKeyguardGone = mActivityIntentHelper.wouldLaunchResolverActivity(
- pendingIntent.getIntent(), mLockscreenUserManager.getCurrentUserId());
+ final boolean afterKeyguardGone = mActivityIntentHelper
+ .wouldPendingLaunchResolverActivity(pendingIntent,
+ mLockscreenUserManager.getCurrentUserId());
mActivityStarter.dismissKeyguardThenExecute(() -> {
mActionClickLogger.logKeyguardGone(pendingIntent);
diff --git a/packages/SystemUI/src/com/android/systemui/util/SysuiLifecycle.java b/packages/SystemUI/src/com/android/systemui/util/SysuiLifecycle.java
deleted file mode 100644
index d73175310802..000000000000
--- a/packages/SystemUI/src/com/android/systemui/util/SysuiLifecycle.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.util;
-
-import static androidx.lifecycle.Lifecycle.State.DESTROYED;
-import static androidx.lifecycle.Lifecycle.State.RESUMED;
-
-import android.view.View;
-import android.view.View.OnAttachStateChangeListener;
-
-import androidx.annotation.NonNull;
-import androidx.lifecycle.Lifecycle;
-import androidx.lifecycle.LifecycleOwner;
-import androidx.lifecycle.LifecycleRegistry;
-
-/**
- * Tools for generating lifecycle from sysui objects.
- */
-public class SysuiLifecycle {
-
- private SysuiLifecycle() {
- }
-
- /**
- * Get a lifecycle that will be put into the resumed state when the view is attached
- * and goes to the destroyed state when the view is detached.
- */
- public static LifecycleOwner viewAttachLifecycle(View v) {
- return new ViewLifecycle(v);
- }
-
- private static class ViewLifecycle implements LifecycleOwner, OnAttachStateChangeListener {
- private final LifecycleRegistry mLifecycle = new LifecycleRegistry(this);
-
- ViewLifecycle(View v) {
- v.addOnAttachStateChangeListener(this);
- if (v.isAttachedToWindow()) {
- mLifecycle.markState(RESUMED);
- }
- }
-
- @NonNull
- @Override
- public Lifecycle getLifecycle() {
- return mLifecycle;
- }
-
- @Override
- public void onViewAttachedToWindow(View v) {
- mLifecycle.markState(RESUMED);
- }
-
- @Override
- public void onViewDetachedFromWindow(View v) {
- mLifecycle.markState(DESTROYED);
- }
- }
-}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/dreams/complication/ComplicationTypesUpdaterTest.java b/packages/SystemUI/tests/src/com/android/systemui/dreams/complication/ComplicationTypesUpdaterTest.java
index 09976e0e6192..571dd3d1faf3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/dreams/complication/ComplicationTypesUpdaterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/dreams/complication/ComplicationTypesUpdaterTest.java
@@ -106,7 +106,7 @@ public class ComplicationTypesUpdaterTest extends SysuiTestCase {
private ContentObserver captureSettingsObserver() {
verify(mSecureSettings).registerContentObserverForUser(
- eq(Settings.Secure.SCREENSAVER_ENABLED_COMPLICATIONS),
+ eq(Settings.Secure.SCREENSAVER_COMPLICATIONS_ENABLED),
mSettingsObserverCaptor.capture(), eq(UserHandle.myUserId()));
return mSettingsObserverCaptor.getValue();
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/screenshot/TakeScreenshotServiceTest.kt b/packages/SystemUI/tests/src/com/android/systemui/screenshot/TakeScreenshotServiceTest.kt
new file mode 100644
index 000000000000..83e56daf1fbc
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/screenshot/TakeScreenshotServiceTest.kt
@@ -0,0 +1,237 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.systemui.screenshot
+
+import android.app.Application
+import android.app.admin.DevicePolicyManager
+import android.app.admin.DevicePolicyResources.Strings.SystemUi.SCREENSHOT_BLOCKED_BY_ADMIN
+import android.app.admin.DevicePolicyResourcesManager
+import android.content.ComponentName
+import android.graphics.Bitmap
+import android.graphics.Bitmap.Config.HARDWARE
+import android.graphics.ColorSpace
+import android.graphics.Insets
+import android.graphics.Rect
+import android.hardware.HardwareBuffer
+import android.os.UserHandle
+import android.os.UserManager
+import android.testing.AndroidTestingRunner
+import android.view.WindowManager.ScreenshotSource.SCREENSHOT_KEY_CHORD
+import android.view.WindowManager.ScreenshotSource.SCREENSHOT_OVERVIEW
+import android.view.WindowManager.TAKE_SCREENSHOT_FULLSCREEN
+import android.view.WindowManager.TAKE_SCREENSHOT_PROVIDED_IMAGE
+import android.view.WindowManager.TAKE_SCREENSHOT_SELECTED_REGION
+import com.android.internal.logging.testing.UiEventLoggerFake
+import com.android.internal.util.ScreenshotHelper
+import com.android.internal.util.ScreenshotHelper.ScreenshotRequest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.flags.FakeFeatureFlags
+import com.android.systemui.flags.Flags.SCREENSHOT_REQUEST_PROCESSOR
+import com.android.systemui.screenshot.ScreenshotEvent.SCREENSHOT_REQUESTED_KEY_CHORD
+import com.android.systemui.screenshot.ScreenshotEvent.SCREENSHOT_REQUESTED_OVERVIEW
+import com.android.systemui.screenshot.TakeScreenshotService.RequestCallback
+import com.android.systemui.util.mockito.any
+import com.android.systemui.util.mockito.argThat
+import com.android.systemui.util.mockito.eq
+import com.android.systemui.util.mockito.mock
+import org.junit.Assert.assertEquals
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.ArgumentMatchers.isNull
+import org.mockito.Mockito.verify
+import org.mockito.Mockito.verifyZeroInteractions
+import org.mockito.Mockito.`when` as whenever
+
+private const val USER_ID = 1
+private const val TASK_ID = 1
+
+@RunWith(AndroidTestingRunner::class)
+class TakeScreenshotServiceTest : SysuiTestCase() {
+
+ private val application = mock<Application>()
+ private val controller = mock<ScreenshotController>()
+ private val userManager = mock<UserManager>()
+ private val requestProcessor = mock<RequestProcessor>()
+ private val devicePolicyManager = mock<DevicePolicyManager>()
+ private val devicePolicyResourcesManager = mock<DevicePolicyResourcesManager>()
+ private val notificationsController = mock<ScreenshotNotificationsController>()
+ private val callback = mock<RequestCallback>()
+
+ private val eventLogger = UiEventLoggerFake()
+ private val flags = FakeFeatureFlags()
+ private val topComponent = ComponentName(mContext, TakeScreenshotServiceTest::class.java)
+
+ private val service = TakeScreenshotService(
+ controller, userManager, devicePolicyManager, eventLogger,
+ notificationsController, mContext, Runnable::run, flags, requestProcessor)
+
+ @Before
+ fun setUp() {
+ whenever(devicePolicyManager.resources).thenReturn(devicePolicyResourcesManager)
+ whenever(devicePolicyManager.getScreenCaptureDisabled(
+ /* admin component (null: any admin) */ isNull(), eq(UserHandle.USER_ALL)))
+ .thenReturn(false)
+ whenever(userManager.isUserUnlocked).thenReturn(true)
+
+ flags.set(SCREENSHOT_REQUEST_PROCESSOR, false)
+
+ service.attach(
+ mContext,
+ /* thread = */ null,
+ /* className = */ null,
+ /* token = */ null,
+ application,
+ /* activityManager = */ null)
+ }
+
+ @Test
+ fun testServiceLifecycle() {
+ service.onCreate()
+ service.onBind(null /* unused: Intent */)
+
+ service.onUnbind(null /* unused: Intent */)
+ verify(controller).removeWindow()
+
+ service.onDestroy()
+ verify(controller).onDestroy()
+ }
+
+ @Test
+ fun takeScreenshotFullscreen() {
+ val request = ScreenshotRequest(
+ TAKE_SCREENSHOT_FULLSCREEN,
+ SCREENSHOT_KEY_CHORD,
+ topComponent)
+
+ service.handleRequest(request, { /* onSaved */ }, callback)
+
+ verify(controller).takeScreenshotFullscreen(
+ eq(topComponent),
+ /* onSavedListener = */ any(),
+ /* requestCallback = */ any())
+
+ assertEquals("Expected one UiEvent", eventLogger.numLogs(), 1)
+ val logEvent = eventLogger.get(0)
+
+ assertEquals("Expected SCREENSHOT_REQUESTED UiEvent",
+ logEvent.eventId, SCREENSHOT_REQUESTED_KEY_CHORD.id)
+ assertEquals("Expected supplied package name",
+ topComponent.packageName, eventLogger.get(0).packageName)
+ }
+
+ @Test
+ fun takeScreenshotPartial() {
+ val request = ScreenshotRequest(
+ TAKE_SCREENSHOT_SELECTED_REGION,
+ SCREENSHOT_KEY_CHORD,
+ /* topComponent = */ null)
+
+ service.handleRequest(request, { /* onSaved */ }, callback)
+
+ verify(controller).takeScreenshotPartial(
+ /* topComponent = */ isNull(),
+ /* onSavedListener = */ any(),
+ /* requestCallback = */ any())
+
+ assertEquals("Expected one UiEvent", eventLogger.numLogs(), 1)
+ val logEvent = eventLogger.get(0)
+
+ assertEquals("Expected SCREENSHOT_REQUESTED UiEvent",
+ logEvent.eventId, SCREENSHOT_REQUESTED_KEY_CHORD.id)
+ assertEquals("Expected empty package name in UiEvent", "", eventLogger.get(0).packageName)
+ }
+
+ @Test
+ fun takeScreenshotProvidedImage() {
+ val bounds = Rect(50, 50, 150, 150)
+ val bitmap = makeHardwareBitmap(100, 100)
+ val bitmapBundle = ScreenshotHelper.HardwareBitmapBundler.hardwareBitmapToBundle(bitmap)
+
+ val request = ScreenshotRequest(TAKE_SCREENSHOT_PROVIDED_IMAGE, SCREENSHOT_OVERVIEW,
+ bitmapBundle, bounds, Insets.NONE, TASK_ID, USER_ID, topComponent)
+
+ service.handleRequest(request, { /* onSaved */ }, callback)
+
+ verify(controller).handleImageAsScreenshot(
+ argThat { b -> b.equalsHardwareBitmap(bitmap) },
+ eq(bounds),
+ eq(Insets.NONE), eq(TASK_ID), eq(USER_ID), eq(topComponent),
+ /* onSavedListener = */ any(), /* requestCallback = */ any())
+
+ assertEquals("Expected one UiEvent", eventLogger.numLogs(), 1)
+ val logEvent = eventLogger.get(0)
+
+ assertEquals("Expected SCREENSHOT_REQUESTED_* UiEvent",
+ logEvent.eventId, SCREENSHOT_REQUESTED_OVERVIEW.id)
+ assertEquals("Expected supplied package name",
+ topComponent.packageName, eventLogger.get(0).packageName)
+ }
+
+ @Test
+ fun takeScreenshotFullscreen_userLocked() {
+ whenever(userManager.isUserUnlocked).thenReturn(false)
+
+ val request = ScreenshotRequest(
+ TAKE_SCREENSHOT_FULLSCREEN,
+ SCREENSHOT_KEY_CHORD,
+ topComponent)
+
+ service.handleRequest(request, { /* onSaved */ }, callback)
+
+ verify(notificationsController).notifyScreenshotError(anyInt())
+ verify(callback).reportError()
+ verifyZeroInteractions(controller)
+ }
+
+ @Test
+ fun takeScreenshotFullscreen_screenCaptureDisabled_allUsers() {
+ whenever(devicePolicyManager.getScreenCaptureDisabled(
+ isNull(), eq(UserHandle.USER_ALL))
+ ).thenReturn(true)
+
+ whenever(devicePolicyResourcesManager.getString(
+ eq(SCREENSHOT_BLOCKED_BY_ADMIN),
+ /* Supplier<String> */ any(),
+ )).thenReturn("SCREENSHOT_BLOCKED_BY_ADMIN")
+
+ val request = ScreenshotRequest(
+ TAKE_SCREENSHOT_FULLSCREEN,
+ SCREENSHOT_KEY_CHORD,
+ topComponent)
+
+ service.handleRequest(request, { /* onSaved */ }, callback)
+
+ // error shown: Toast.makeText(...).show(), untestable
+ verify(callback).reportError()
+ verifyZeroInteractions(controller)
+ }
+}
+
+private fun Bitmap.equalsHardwareBitmap(other: Bitmap): Boolean {
+ return config == HARDWARE &&
+ other.config == HARDWARE &&
+ hardwareBuffer == other.hardwareBuffer &&
+ colorSpace == other.colorSpace
+}
+
+/** A hardware Bitmap is mandated by use of ScreenshotHelper.HardwareBitmapBundler */
+private fun makeHardwareBitmap(width: Int, height: Int): Bitmap {
+ val buffer = HardwareBuffer.create(width, height, HardwareBuffer.RGBA_8888, 1,
+ HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE)
+ return Bitmap.wrapHardwareBuffer(buffer, ColorSpace.get(ColorSpace.Named.SRGB))!!
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java
index 95211c0c8ec8..7d28871e340c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java
@@ -47,7 +47,6 @@ import android.content.ContentResolver;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
-import android.graphics.PointF;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
@@ -764,10 +763,8 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase {
@Test
public void testSetDozing_notifiesNsslAndStateController() {
- mNotificationPanelViewController.setDozing(true /* dozing */, false /* animate */,
- null /* touch */);
- verify(mNotificationStackScrollLayoutController)
- .setDozing(eq(true), eq(false), eq(null));
+ mNotificationPanelViewController.setDozing(true /* dozing */, false /* animate */);
+ verify(mNotificationStackScrollLayoutController).setDozing(eq(true), eq(false));
assertThat(mStatusBarStateController.getDozeAmount()).isEqualTo(1f);
}
@@ -908,7 +905,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase {
setDozing(/* dozing= */ true, /* dozingAlwaysOn= */ true);
- assertThat(isKeyguardStatusViewCentered()).isTrue();
+ assertKeyguardStatusViewCentered();
}
@Test
@@ -919,7 +916,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase {
setDozing(/* dozing= */ true, /* dozingAlwaysOn= */ false);
- assertThat(isKeyguardStatusViewCentered()).isFalse();
+ assertKeyguardStatusViewNotCentered();
}
@Test
@@ -930,19 +927,19 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase {
setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ true);
- assertThat(isKeyguardStatusViewCentered()).isFalse();
+ assertKeyguardStatusViewNotCentered();
}
@Test
- public void keyguardStatusView_splitShade_pulsing_isCentered() {
+ public void keyguardStatusView_splitShade_pulsing_isNotCentered() {
when(mNotificationStackScrollLayoutController.getVisibleNotificationCount()).thenReturn(2);
when(mNotificationListContainer.hasPulsingNotifications()).thenReturn(true);
mStatusBarStateController.setState(KEYGUARD);
enableSplitShade(/* enabled= */ true);
- setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ true);
+ setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ false);
- assertThat(isKeyguardStatusViewCentered()).isFalse();
+ assertKeyguardStatusViewNotCentered();
}
@Test
@@ -952,9 +949,9 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase {
mStatusBarStateController.setState(KEYGUARD);
enableSplitShade(/* enabled= */ true);
- setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ true);
+ setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ false);
- assertThat(isKeyguardStatusViewCentered()).isFalse();
+ assertKeyguardStatusViewNotCentered();
}
@Test
@@ -967,7 +964,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase {
mStatusBarStateController.setState(KEYGUARD);
setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ false);
- assertThat(isKeyguardStatusViewCentered()).isFalse();
+ assertKeyguardStatusViewCentered();
}
@Test
@@ -1212,16 +1209,31 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase {
}
@Test
- public void testSwitchesToBigClockInSplitShadeOnAod() {
+ public void clockSize_mediaShowing_inSplitShade_onAod_isLarge() {
+ when(mDozeParameters.getAlwaysOn()).thenReturn(true);
mStatusBarStateController.setState(KEYGUARD);
enableSplitShade(/* enabled= */ true);
when(mMediaDataManager.hasActiveMediaOrRecommendation()).thenReturn(true);
when(mNotificationStackScrollLayoutController.getVisibleNotificationCount()).thenReturn(2);
clearInvocations(mKeyguardStatusViewController);
- mNotificationPanelViewController.setDozing(true, false, null);
+ mNotificationPanelViewController.setDozing(/* dozing= */ true, /* animate= */ false);
- verify(mKeyguardStatusViewController).displayClock(LARGE, /* animate */ true);
+ verify(mKeyguardStatusViewController).displayClock(LARGE, /* animate= */ true);
+ }
+
+ @Test
+ public void clockSize_mediaShowing_inSplitShade_screenOff_notAod_isSmall() {
+ when(mDozeParameters.getAlwaysOn()).thenReturn(false);
+ mStatusBarStateController.setState(KEYGUARD);
+ enableSplitShade(/* enabled= */ true);
+ when(mMediaDataManager.hasActiveMediaOrRecommendation()).thenReturn(true);
+ when(mNotificationStackScrollLayoutController.getVisibleNotificationCount()).thenReturn(2);
+ clearInvocations(mKeyguardStatusViewController);
+
+ mNotificationPanelViewController.setDozing(/* dozing= */ true, /* animate= */ false);
+
+ verify(mKeyguardStatusViewController).displayClock(SMALL, /* animate= */ true);
}
@Test
@@ -1233,7 +1245,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase {
when(mMediaDataManager.hasActiveMedia()).thenReturn(true);
when(mNotificationStackScrollLayoutController.getVisibleNotificationCount()).thenReturn(2);
- mNotificationPanelViewController.setDozing(true, false, null);
+ mNotificationPanelViewController.setDozing(true, false);
verify(mKeyguardStatusViewController).displayClock(LARGE, /* animate */ false);
}
@@ -1547,14 +1559,19 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase {
when(mDozeParameters.getAlwaysOn()).thenReturn(dozingAlwaysOn);
mNotificationPanelViewController.setDozing(
/* dozing= */ dozing,
- /* animate= */ false,
- /* wakeUpTouchLocation= */ new PointF()
+ /* animate= */ false
);
}
- private boolean isKeyguardStatusViewCentered() {
+ private void assertKeyguardStatusViewCentered() {
+ mNotificationPanelViewController.updateResources();
+ assertThat(getConstraintSetLayout(R.id.keyguard_status_view).endToEnd).isAnyOf(
+ ConstraintSet.PARENT_ID, ConstraintSet.UNSET);
+ }
+
+ private void assertKeyguardStatusViewNotCentered() {
mNotificationPanelViewController.updateResources();
- return getConstraintSetLayout(R.id.keyguard_status_view).endToEnd
- == ConstraintSet.PARENT_ID;
+ assertThat(getConstraintSetLayout(R.id.keyguard_status_view).endToEnd).isEqualTo(
+ R.id.qs_edge_guideline);
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarStateControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarStateControllerImplTest.kt
index be631afdd1a9..1d8e5dec5c50 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarStateControllerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarStateControllerImplTest.kt
@@ -38,8 +38,8 @@ import org.mockito.ArgumentMatchers.eq
import org.mockito.Mock
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
-import org.mockito.MockitoAnnotations
import org.mockito.Mockito.`when` as whenever
+import org.mockito.MockitoAnnotations
@SmallTest
@RunWith(AndroidTestingRunner::class)
@@ -89,8 +89,8 @@ class StatusBarStateControllerImplTest : SysuiTestCase() {
val listener = mock(StatusBarStateController.StateListener::class.java)
controller.addCallback(listener)
- controller.setDozeAmount(0.5f, false /* animated */)
- controller.setDozeAmount(0.5f, false /* animated */)
+ controller.setAndInstrumentDozeAmount(null, 0.5f, false /* animated */)
+ controller.setAndInstrumentDozeAmount(null, 0.5f, false /* animated */)
verify(listener).onDozeAmountChanged(eq(0.5f), anyFloat())
}
@@ -135,7 +135,7 @@ class StatusBarStateControllerImplTest : SysuiTestCase() {
@Test
fun testSetDozeAmount_immediatelyChangesDozeAmount_lockscreenTransitionFromAod() {
// Put controller in AOD state
- controller.setDozeAmount(1f, false)
+ controller.setAndInstrumentDozeAmount(null, 1f, false)
// When waking from doze, CentralSurfaces#updateDozingState will update the dozing state
// before the doze amount changes
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt
index 214ba16dfc44..64d025628754 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt
@@ -98,7 +98,7 @@ class ChannelEditorDialogControllerTest : SysuiTestCase() {
@Test
fun testPrepareDialogForApp_onlyDefaultChannel() {
- group.channels = listOf(channelDefault)
+ group.addChannel(channelDefault)
controller.prepareDialogForApp(TEST_APP_NAME, TEST_PACKAGE_NAME, TEST_UID,
setOf(channelDefault), appIcon, clickListener)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
index f8b39e8cff71..137842ef314f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
@@ -28,7 +28,6 @@ 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.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -58,8 +57,8 @@ import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.notification.AboveShelfChangedListener;
import com.android.systemui.statusbar.notification.FeedbackIcon;
-import com.android.systemui.statusbar.notification.row.ExpandableView.OnHeightChangedListener;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.row.ExpandableView.OnHeightChangedListener;
import com.android.systemui.statusbar.notification.stack.NotificationChildrenContainer;
import org.junit.Assert;
@@ -260,17 +259,6 @@ public class ExpandableNotificationRowTest extends SysuiTestCase {
}
@Test
- public void setNeedsRedactionFreesViewWhenFalse() throws Exception {
- ExpandableNotificationRow row = mNotificationTestHelper.createRow(FLAG_CONTENT_VIEW_ALL);
- row.setNeedsRedaction(true);
- row.getPublicLayout().setVisibility(View.GONE);
-
- row.setNeedsRedaction(false);
- TestableLooper.get(this).processAllMessages();
- assertNull(row.getPublicLayout().getContractedChild());
- }
-
- @Test
public void testAboveShelfChangedListenerCalled() throws Exception {
ExpandableNotificationRow row = mNotificationTestHelper.createRow();
AboveShelfChangedListener listener = mock(AboveShelfChangedListener.class);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
index de43a1fabab6..2b805089a430 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
@@ -37,7 +37,6 @@ import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
-import android.content.Intent;
import android.os.Handler;
import android.os.RemoteException;
import android.os.UserHandle;
@@ -135,8 +134,6 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
@Mock
private PendingIntent mContentIntent;
@Mock
- private Intent mContentIntentInner;
- @Mock
private OnUserInteractionCallback mOnUserInteractionCallback;
@Mock
private Runnable mFutureDismissalRunnable;
@@ -159,7 +156,6 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
MockitoAnnotations.initMocks(this);
when(mContentIntent.isActivity()).thenReturn(true);
when(mContentIntent.getCreatorUserHandle()).thenReturn(UserHandle.of(1));
- when(mContentIntent.getIntent()).thenReturn(mContentIntentInner);
NotificationTestHelper notificationTestHelper = new NotificationTestHelper(
mContext,
@@ -374,7 +370,6 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase {
eq(entry.getKey()), any(NotificationVisibility.class));
// The content intent should NOT be sent on click.
- verify(mContentIntent).getIntent();
verify(mContentIntent).isActivity();
verifyNoMoreInteractions(mContentIntent);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java
deleted file mode 100644
index 4f509eaaadde..000000000000
--- a/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.util;
-
-import static androidx.lifecycle.Lifecycle.Event.ON_CREATE;
-import static androidx.lifecycle.Lifecycle.Event.ON_DESTROY;
-import static androidx.lifecycle.Lifecycle.Event.ON_PAUSE;
-import static androidx.lifecycle.Lifecycle.Event.ON_RESUME;
-import static androidx.lifecycle.Lifecycle.Event.ON_START;
-import static androidx.lifecycle.Lifecycle.Event.ON_STOP;
-
-import static com.android.systemui.util.SysuiLifecycle.viewAttachLifecycle;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-import android.testing.TestableLooper.RunWithLooper;
-import android.testing.ViewUtils;
-import android.view.View;
-
-import androidx.lifecycle.Lifecycle;
-import androidx.lifecycle.LifecycleEventObserver;
-import androidx.lifecycle.LifecycleOwner;
-import androidx.test.filters.SmallTest;
-
-import com.android.systemui.SysuiTestCase;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWithLooper(setAsMainLooper = true)
-@RunWith(AndroidTestingRunner.class)
-@SmallTest
-public class SysuiLifecycleTest extends SysuiTestCase {
-
- private View mView;
-
- @Before
- public void setUp() {
- mView = new View(mContext);
- }
-
- @After
- public void tearDown() {
- if (mView.isAttachedToWindow()) {
- ViewUtils.detachView(mView);
- TestableLooper.get(this).processAllMessages();
- }
- }
-
- @Test
- public void testAttach() {
- LifecycleEventObserver observer = mock(LifecycleEventObserver.class);
- LifecycleOwner lifecycle = viewAttachLifecycle(mView);
- lifecycle.getLifecycle().addObserver(observer);
-
- ViewUtils.attachView(mView);
- TestableLooper.get(this).processAllMessages();
-
- verify(observer).onStateChanged(eq(lifecycle), eq(ON_CREATE));
- verify(observer).onStateChanged(eq(lifecycle), eq(ON_START));
- verify(observer).onStateChanged(eq(lifecycle), eq(ON_RESUME));
- }
-
- @Test
- public void testDetach() {
- LifecycleEventObserver observer = mock(LifecycleEventObserver.class);
- LifecycleOwner lifecycle = viewAttachLifecycle(mView);
- lifecycle.getLifecycle().addObserver(observer);
-
- ViewUtils.attachView(mView);
- TestableLooper.get(this).processAllMessages();
-
- ViewUtils.detachView(mView);
- TestableLooper.get(this).processAllMessages();
-
- verify(observer).onStateChanged(eq(lifecycle), eq(ON_PAUSE));
- verify(observer).onStateChanged(eq(lifecycle), eq(ON_STOP));
- verify(observer).onStateChanged(eq(lifecycle), eq(ON_DESTROY));
- }
-
- @Test
- public void testStateBeforeAttach() {
- // WHEN a lifecycle is obtained from a view
- LifecycleOwner lifecycle = viewAttachLifecycle(mView);
- // THEN the lifecycle state should be INITIAZED
- assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(
- Lifecycle.State.INITIALIZED);
- }
-
- @Test
- public void testStateAfterAttach() {
- // WHEN a lifecycle is obtained from a view
- LifecycleOwner lifecycle = viewAttachLifecycle(mView);
- // AND the view is attached
- ViewUtils.attachView(mView);
- TestableLooper.get(this).processAllMessages();
- // THEN the lifecycle state should be RESUMED
- assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(Lifecycle.State.RESUMED);
- }
-
- @Test
- public void testStateAfterDetach() {
- // WHEN a lifecycle is obtained from a view
- LifecycleOwner lifecycle = viewAttachLifecycle(mView);
- // AND the view is detached
- ViewUtils.attachView(mView);
- TestableLooper.get(this).processAllMessages();
- ViewUtils.detachView(mView);
- TestableLooper.get(this).processAllMessages();
- // THEN the lifecycle state should be DESTROYED
- assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(Lifecycle.State.DESTROYED);
- }
-
- @Test
- public void testStateAfterReattach() {
- // WHEN a lifecycle is obtained from a view
- LifecycleOwner lifecycle = viewAttachLifecycle(mView);
- // AND the view is re-attached
- ViewUtils.attachView(mView);
- TestableLooper.get(this).processAllMessages();
- ViewUtils.detachView(mView);
- TestableLooper.get(this).processAllMessages();
- ViewUtils.attachView(mView);
- TestableLooper.get(this).processAllMessages();
- // THEN the lifecycle state should still be DESTROYED, err RESUMED?
- assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(Lifecycle.State.RESUMED);
- }
-
- @Test
- public void testStateWhenViewAlreadyAttached() {
- // GIVEN that a view is already attached
- ViewUtils.attachView(mView);
- TestableLooper.get(this).processAllMessages();
- // WHEN a lifecycle is obtained from a view
- LifecycleOwner lifecycle = viewAttachLifecycle(mView);
- // THEN the lifecycle state should be RESUMED
- assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(Lifecycle.State.RESUMED);
- }
-
- @Test
- public void testStateWhenViewAlreadyDetached() {
- // GIVEN that a view is already detached
- ViewUtils.attachView(mView);
- TestableLooper.get(this).processAllMessages();
- ViewUtils.detachView(mView);
- TestableLooper.get(this).processAllMessages();
- // WHEN a lifecycle is obtained from a view
- LifecycleOwner lifecycle = viewAttachLifecycle(mView);
- // THEN the lifecycle state should be INITIALIZED
- assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(
- Lifecycle.State.INITIALIZED);
- }
-}
diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
index fa043f8e02af..265fbc510259 100644
--- a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
+++ b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java
@@ -17,7 +17,6 @@
package com.android.server.companion;
-import static android.Manifest.permission.DELIVER_COMPANION_MESSAGES;
import static android.Manifest.permission.MANAGE_COMPANION_DEVICES;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
@@ -88,7 +87,6 @@ import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.ArraySet;
-import android.util.Base64;
import android.util.ExceptionUtils;
import android.util.Log;
import android.util.Slog;
@@ -756,6 +754,11 @@ public class CompanionDeviceManagerService extends SystemService {
mDevicePresenceMonitor.onSelfManagedDeviceDisconnected(associationId);
}
+ @Override
+ public boolean isCompanionApplicationBound(String packageName, int userId) {
+ return mCompanionAppController.isCompanionApplicationBound(userId, packageName);
+ }
+
private void registerDevicePresenceListenerActive(String packageName, String deviceAddress,
boolean active) throws RemoteException {
if (DEBUG) {
diff --git a/services/core/java/com/android/server/BootReceiver.java b/services/core/java/com/android/server/BootReceiver.java
index b8815454cadb..b33d84c0f275 100644
--- a/services/core/java/com/android/server/BootReceiver.java
+++ b/services/core/java/com/android/server/BootReceiver.java
@@ -16,6 +16,7 @@
package com.android.server;
+import static android.os.ParcelFileDescriptor.MODE_READ_WRITE;
import static android.system.OsConstants.O_RDONLY;
import android.content.BroadcastReceiver;
@@ -26,8 +27,10 @@ import android.os.DropBoxManager;
import android.os.Environment;
import android.os.FileUtils;
import android.os.MessageQueue.OnFileDescriptorEventListener;
+import android.os.ParcelFileDescriptor;
import android.os.RecoverySystem;
import android.os.SystemProperties;
+import android.os.TombstoneWithHeadersProto;
import android.provider.Downloads;
import android.system.ErrnoException;
import android.system.Os;
@@ -38,6 +41,7 @@ import android.util.Slog;
import android.util.TypedXmlPullParser;
import android.util.TypedXmlSerializer;
import android.util.Xml;
+import android.util.proto.ProtoOutputStream;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.MetricsLogger;
@@ -54,6 +58,8 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.attribute.PosixFilePermissions;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
@@ -78,6 +84,11 @@ public class BootReceiver extends BroadcastReceiver {
private static final String TAG_TOMBSTONE = "SYSTEM_TOMBSTONE";
private static final String TAG_TOMBSTONE_PROTO = "SYSTEM_TOMBSTONE_PROTO";
+ private static final String TAG_TOMBSTONE_PROTO_WITH_HEADERS =
+ "SYSTEM_TOMBSTONE_PROTO_WITH_HEADERS";
+
+ // Directory to store temporary tombstones.
+ private static final File TOMBSTONE_TMP_DIR = new File("/data/tombstones");
// The pre-froyo package and class of the system updater, which
// ran in the system process. We need to remove its packages here
@@ -329,7 +340,44 @@ public class BootReceiver extends BroadcastReceiver {
try {
if (proto) {
if (recordFileTimestamp(tombstone, timestamps)) {
- db.addFile(TAG_TOMBSTONE_PROTO, tombstone, 0);
+ // We need to attach the count indicating the number of dropped dropbox entries
+ // due to rate limiting. Do this by enclosing the proto tombsstone in a
+ // container proto that has the dropped entry count and the proto tombstone as
+ // bytes (to avoid the complexity of reading and writing nested protos).
+
+ // Read the proto tombstone file as bytes.
+ final byte[] tombstoneBytes = Files.readAllBytes(tombstone.toPath());
+
+ final File tombstoneProtoWithHeaders = File.createTempFile(
+ tombstone.getName(), ".tmp", TOMBSTONE_TMP_DIR);
+ Files.setPosixFilePermissions(
+ tombstoneProtoWithHeaders.toPath(),
+ PosixFilePermissions.fromString("rw-rw----"));
+
+ // Write the new proto container proto with headers.
+ ParcelFileDescriptor pfd;
+ try {
+ pfd = ParcelFileDescriptor.open(tombstoneProtoWithHeaders, MODE_READ_WRITE);
+
+ ProtoOutputStream protoStream = new ProtoOutputStream(
+ pfd.getFileDescriptor());
+ protoStream.write(TombstoneWithHeadersProto.TOMBSTONE, tombstoneBytes);
+ protoStream.write(
+ TombstoneWithHeadersProto.DROPPED_COUNT,
+ rateLimitResult.droppedCountSinceRateLimitActivated());
+ protoStream.flush();
+
+ // Add the proto to dropbox.
+ db.addFile(TAG_TOMBSTONE_PROTO_WITH_HEADERS, tombstoneProtoWithHeaders, 0);
+ } catch (FileNotFoundException ex) {
+ Slog.e(TAG, "failed to open for write: " + tombstoneProtoWithHeaders, ex);
+ throw ex;
+ } finally {
+ // Remove the temporary file.
+ if (tombstoneProtoWithHeaders != null) {
+ tombstoneProtoWithHeaders.delete();
+ }
+ }
}
} else {
// Add the header indicating how many events have been dropped due to rate limiting.
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index 0b858cf38d44..f7833b0f36fd 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -339,7 +339,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
private int[] mDataConnectionNetworkType;
- private ArrayList<List<CellInfo>> mCellInfo = null;
+ private ArrayList<List<CellInfo>> mCellInfo;
private Map<Integer, List<EmergencyNumber>> mEmergencyNumberList;
@@ -725,7 +725,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mMessageWaiting[i] = false;
mCallForwarding[i] = false;
mCellIdentity[i] = null;
- mCellInfo.add(i, null);
+ mCellInfo.add(i, Collections.EMPTY_LIST);
mImsReasonInfo.add(i, null);
mSrvccState[i] = TelephonyManager.SRVCC_STATE_HANDOVER_NONE;
mCallDisconnectCause[i] = DisconnectCause.NOT_VALID;
@@ -802,7 +802,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mCallNetworkType = new int[numPhones];
mCallAttributes = new CallAttributes[numPhones];
mPreciseDataConnectionStates = new ArrayList<>();
- mCellInfo = new ArrayList<>();
+ mCellInfo = new ArrayList<>(numPhones);
mImsReasonInfo = new ArrayList<>();
mEmergencyNumberList = new HashMap<>();
mOutgoingCallEmergencyNumber = new EmergencyNumber[numPhones];
@@ -832,7 +832,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
mMessageWaiting[i] = false;
mCallForwarding[i] = false;
mCellIdentity[i] = null;
- mCellInfo.add(i, null);
+ mCellInfo.add(i, Collections.EMPTY_LIST);
mImsReasonInfo.add(i, null);
mSrvccState[i] = TelephonyManager.SRVCC_STATE_HANDOVER_NONE;
mCallDisconnectCause[i] = DisconnectCause.NOT_VALID;
@@ -1803,10 +1803,17 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
if (!checkNotifyPermission("notifyCellInfoForSubscriber()")) {
return;
}
+
if (VDBG) {
log("notifyCellInfoForSubscriber: subId=" + subId
+ " cellInfo=" + cellInfo);
}
+
+ if (cellInfo == null) {
+ loge("notifyCellInfoForSubscriber() received a null list");
+ cellInfo = Collections.EMPTY_LIST;
+ }
+
int phoneId = getPhoneIdFromSubId(subId);
synchronized (mRecords) {
if (validatePhoneId(phoneId)) {
@@ -2987,8 +2994,8 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub {
pw.println("mBarringInfo=" + mBarringInfo.get(i));
pw.println("mCarrierNetworkChangeState=" + mCarrierNetworkChangeState[i]);
pw.println("mTelephonyDisplayInfo=" + mTelephonyDisplayInfos[i]);
- pw.println("mIsDataEnabled=" + mIsDataEnabled);
- pw.println("mDataEnabledReason=" + mDataEnabledReason);
+ pw.println("mIsDataEnabled=" + mIsDataEnabled[i]);
+ pw.println("mDataEnabledReason=" + mDataEnabledReason[i]);
pw.println("mAllowedNetworkTypeReason=" + mAllowedNetworkTypeReason[i]);
pw.println("mAllowedNetworkTypeValue=" + mAllowedNetworkTypeValue[i]);
pw.println("mPhysicalChannelConfigs=" + mPhysicalChannelConfigs.get(i));
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 734f45523618..a0c2ad57241b 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -2401,13 +2401,13 @@ public class ActivityManagerService extends IActivityManager.Stub
mEnableOffloadQueue = SystemProperties.getBoolean(
"persist.device_config.activity_manager_native_boot.offload_queue_enabled", true);
- mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
+ mFgBroadcastQueue = new BroadcastQueueImpl(this, mHandler,
"foreground", foreConstants, false);
- mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
+ mBgBroadcastQueue = new BroadcastQueueImpl(this, mHandler,
"background", backConstants, true);
- mBgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
+ mBgOffloadBroadcastQueue = new BroadcastQueueImpl(this, mHandler,
"offload_bg", offloadConstants, true);
- mFgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
+ mFgOffloadBroadcastQueue = new BroadcastQueueImpl(this, mHandler,
"offload_fg", foreConstants, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
@@ -10626,8 +10626,7 @@ public class ActivityManagerService extends IActivityManager.Stub
if (!onlyHistory && !onlyReceivers && dumpAll) {
pw.println();
for (BroadcastQueue queue : mBroadcastQueues) {
- pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
- + queue.mBroadcastsScheduled);
+ pw.println(" Queue " + queue.toString() + ": " + queue.describeState());
}
pw.println(" mHandler:");
mHandler.dump(new PrintWriterPrinter(pw), " ");
@@ -13082,17 +13081,23 @@ public class ActivityManagerService extends IActivityManager.Stub
}
boolean isPendingBroadcastProcessLocked(int pid) {
- return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
- || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
- || mBgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid)
- || mFgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid);
+ for (BroadcastQueue queue : mBroadcastQueues) {
+ BroadcastRecord r = queue.getPendingBroadcastLocked();
+ if (r != null && r.curApp.getPid() == pid) {
+ return true;
+ }
+ }
+ return false;
}
boolean isPendingBroadcastProcessLocked(ProcessRecord app) {
- return mFgBroadcastQueue.isPendingBroadcastProcessLocked(app)
- || mBgBroadcastQueue.isPendingBroadcastProcessLocked(app)
- || mBgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(app)
- || mFgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(app);
+ for (BroadcastQueue queue : mBroadcastQueues) {
+ BroadcastRecord r = queue.getPendingBroadcastLocked();
+ if (r != null && r.curApp == app) {
+ return true;
+ }
+ }
+ return false;
}
void skipPendingBroadcastLocked(int pid) {
@@ -13114,7 +13119,6 @@ public class ActivityManagerService extends IActivityManager.Stub
void updateUidReadyForBootCompletedBroadcastLocked(int uid) {
for (BroadcastQueue queue : mBroadcastQueues) {
queue.updateUidReadyForBootCompletedBroadcastLocked(uid);
- queue.scheduleBroadcastsLocked();
}
}
@@ -13364,8 +13368,7 @@ public class ActivityManagerService extends IActivityManager.Stub
receivers, null, 0, null, null, false, true, true, -1, false, null,
false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */,
null /* filterExtrasForReceiver */);
- queue.enqueueParallelBroadcastLocked(r);
- queue.scheduleBroadcastsLocked();
+ queue.enqueueBroadcastLocked(r);
}
}
@@ -14243,13 +14246,7 @@ public class ActivityManagerService extends IActivityManager.Stub
sticky, false, userId, allowBackgroundActivityStarts,
backgroundActivityStartsToken, timeoutExempt, filterExtrasForReceiver);
if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
- final boolean replaced = replacePending
- && (queue.replaceParallelBroadcastLocked(r) != null);
- // Note: We assume resultTo is null for non-ordered broadcasts.
- if (!replaced) {
- queue.enqueueParallelBroadcastLocked(r);
- queue.scheduleBroadcastsLocked();
- }
+ queue.enqueueBroadcastLocked(r);
registeredReceivers = null;
NR = 0;
}
@@ -14342,31 +14339,7 @@ public class ActivityManagerService extends IActivityManager.Stub
backgroundActivityStartsToken, timeoutExempt, filterExtrasForReceiver);
if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
-
- final BroadcastRecord oldRecord =
- replacePending ? queue.replaceOrderedBroadcastLocked(r) : null;
- if (oldRecord != null) {
- // Replaced, fire the result-to receiver.
- if (oldRecord.resultTo != null) {
- final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent);
- try {
- oldRecord.mIsReceiverAppRunning = true;
- oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
- oldRecord.intent,
- Activity.RESULT_CANCELED, null, null,
- false, false, oldRecord.userId, oldRecord.callingUid, callingUid,
- SystemClock.uptimeMillis() - oldRecord.enqueueTime, 0);
- } catch (RemoteException e) {
- Slog.w(TAG, "Failure ["
- + queue.mQueueName + "] sending broadcast result of "
- + intent, e);
-
- }
- }
- } else {
- queue.enqueueOrderedBroadcastLocked(r);
- queue.scheduleBroadcastsLocked();
- }
+ queue.enqueueBroadcastLocked(r);
} else {
// There was nobody interested in the broadcast, but we still want to record
// that it happened.
@@ -15186,7 +15159,7 @@ public class ActivityManagerService extends IActivityManager.Stub
// It's not the current receiver, but it might be starting up to become one
for (BroadcastQueue queue : mBroadcastQueues) {
- final BroadcastRecord r = queue.mPendingBroadcast;
+ final BroadcastRecord r = queue.getPendingBroadcastLocked();
if (r != null && r.curApp == app) {
// found it; report which queue it's in
receivingQueues.add(queue);
@@ -15301,7 +15274,7 @@ public class ActivityManagerService extends IActivityManager.Stub
@GuardedBy("this")
final boolean canGcNowLocked() {
for (BroadcastQueue q : mBroadcastQueues) {
- if (!q.mParallelBroadcasts.isEmpty() || !q.mDispatcher.isIdle()) {
+ if (!q.isIdle()) {
return false;
}
}
@@ -17890,7 +17863,7 @@ public class ActivityManagerService extends IActivityManager.Stub
pw.flush();
}
Slog.v(TAG, msg);
- queue.cancelDeferrals();
+ queue.flush();
idle = false;
}
}
diff --git a/services/core/java/com/android/server/am/BroadcastDispatcher.java b/services/core/java/com/android/server/am/BroadcastDispatcher.java
index 49477ad75302..e9a36e05c6c1 100644
--- a/services/core/java/com/android/server/am/BroadcastDispatcher.java
+++ b/services/core/java/com/android/server/am/BroadcastDispatcher.java
@@ -162,7 +162,7 @@ public class BroadcastDispatcher {
}
private final Object mLock;
- private final BroadcastQueue mQueue;
+ private final BroadcastQueueImpl mQueue;
private final BroadcastConstants mConstants;
private final Handler mHandler;
private AlarmManagerInternal mAlarm;
@@ -489,7 +489,7 @@ public class BroadcastDispatcher {
/**
* Constructed & sharing a lock with its associated BroadcastQueue instance
*/
- public BroadcastDispatcher(BroadcastQueue queue, BroadcastConstants constants,
+ public BroadcastDispatcher(BroadcastQueueImpl queue, BroadcastConstants constants,
Handler handler, Object lock) {
mQueue = queue;
mConstants = constants;
diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java
index 31d9f96d46e4..d0946bec730a 100644
--- a/services/core/java/com/android/server/am/BroadcastQueue.java
+++ b/services/core/java/com/android/server/am/BroadcastQueue.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2012 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,236 +16,40 @@
package com.android.server.am;
-import static android.app.ActivityManager.RESTRICTION_LEVEL_RESTRICTED_BUCKET;
-import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
-import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
-import static android.text.TextUtils.formatSimple;
-
-import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED;
-import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED;
-import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED;
-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;
-import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM;
-import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST;
-import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME;
-import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
-import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_DEFERRAL;
-import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT;
-import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
-import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
-import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
-import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
-import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER;
-import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_START_RECEIVER;
-
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.app.ActivityManager;
-import android.app.AppGlobals;
-import android.app.AppOpsManager;
-import android.app.BroadcastOptions;
-import android.app.IApplicationThread;
-import android.app.PendingIntent;
-import android.app.RemoteServiceException.CannotDeliverBroadcastException;
-import android.app.usage.UsageEvents.Event;
-import android.app.usage.UsageStatsManagerInternal;
-import android.content.ComponentName;
+import android.content.BroadcastReceiver;
import android.content.ContentResolver;
-import android.content.IIntentReceiver;
-import android.content.IIntentSender;
import android.content.Intent;
-import android.content.IntentSender;
-import android.content.pm.ActivityInfo;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PermissionInfo;
-import android.content.pm.ResolveInfo;
-import android.content.pm.UserInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
-import android.os.Looper;
-import android.os.Message;
-import android.os.PowerExemptionManager.ReasonCode;
-import android.os.PowerExemptionManager.TempAllowListType;
-import android.os.Process;
-import android.os.RemoteException;
-import android.os.SystemClock;
-import android.os.Trace;
-import android.os.UserHandle;
-import android.os.UserManager;
-import android.permission.IPermissionManager;
-import android.text.TextUtils;
-import android.util.EventLog;
-import android.util.Slog;
-import android.util.SparseIntArray;
-import android.util.TimeUtils;
import android.util.proto.ProtoOutputStream;
-import com.android.internal.os.TimeoutRecord;
-import com.android.internal.util.ArrayUtils;
-import com.android.internal.util.FrameworkStatsLog;
-import com.android.server.LocalServices;
-import com.android.server.pm.UserManagerInternal;
-
import java.io.FileDescriptor;
import java.io.PrintWriter;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
import java.util.Set;
/**
- * BROADCASTS
- *
- * We keep three broadcast queues and associated bookkeeping, one for those at
- * foreground priority, and one for normal (background-priority) broadcasts, and one to
- * offload special broadcasts that we know take a long time, such as BOOT_COMPLETED.
+ * Queue of broadcast intents and associated bookkeeping.
*/
-public final class BroadcastQueue {
- private static final String TAG = "BroadcastQueue";
- private static final String TAG_MU = TAG + POSTFIX_MU;
- private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
-
- static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
- static final int MAX_BROADCAST_SUMMARY_HISTORY
- = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
+public abstract class BroadcastQueue {
+ public static final String TAG = "BroadcastQueue";
final ActivityManagerService mService;
-
- /**
- * Behavioral parameters such as timeouts and deferral policy, tracking Settings
- * for runtime configurability
- */
+ final Handler mHandler;
final BroadcastConstants mConstants;
-
- /**
- * Recognizable moniker for this queue
- */
+ final BroadcastSkipPolicy mSkipPolicy;
final String mQueueName;
- /**
- * If true, we can delay broadcasts while waiting services to finish in the previous
- * receiver's process.
- */
- final boolean mDelayBehindServices;
-
- /**
- * Lists of all active broadcasts that are to be executed immediately
- * (without waiting for another broadcast to finish). Currently this only
- * contains broadcasts to registered receivers, to avoid spinning up
- * a bunch of processes to execute IntentReceiver components. Background-
- * and foreground-priority broadcasts are queued separately.
- */
- final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
-
- /**
- * Tracking of the ordered broadcast queue, including deferral policy and alarm
- * prioritization.
- */
- final BroadcastDispatcher mDispatcher;
-
- /**
- * Refcounting for completion callbacks of split/deferred broadcasts. The key
- * is an opaque integer token assigned lazily when a broadcast is first split
- * into multiple BroadcastRecord objects.
- */
- final SparseIntArray mSplitRefcounts = new SparseIntArray();
- private int mNextToken = 0;
-
- /**
- * Historical data of past broadcasts, for debugging. This is a ring buffer
- * whose last element is at mHistoryNext.
- */
- final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
- int mHistoryNext = 0;
-
- /**
- * Summary of historical data of past broadcasts, for debugging. This is a
- * ring buffer whose last element is at mSummaryHistoryNext.
- */
- final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
- int mSummaryHistoryNext = 0;
-
- /**
- * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
- * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
- * clock time, not elapsed.
- */
- final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
- final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
- final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
-
- /**
- * Set when we current have a BROADCAST_INTENT_MSG in flight.
- */
- boolean mBroadcastsScheduled = false;
-
- /**
- * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
- */
- boolean mPendingBroadcastTimeoutMessage;
-
- /**
- * Intent broadcasts that we have tried to start, but are
- * waiting for the application's process to be created. We only
- * need one per scheduling class (instead of a list) because we always
- * process broadcasts one at a time, so no others can be started while
- * waiting for this one.
- */
- BroadcastRecord mPendingBroadcast = null;
-
- /**
- * The receiver index that is pending, to restart the broadcast if needed.
- */
- int mPendingBroadcastRecvIndex;
-
- static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
- static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
-
- // log latency metrics for ordered broadcasts during BOOT_COMPLETED processing
- boolean mLogLatencyMetrics = true;
-
- final BroadcastHandler mHandler;
-
- private final class BroadcastHandler extends Handler {
- public BroadcastHandler(Looper looper) {
- super(looper, null, true);
- }
-
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case BROADCAST_INTENT_MSG: {
- if (DEBUG_BROADCAST) Slog.v(
- TAG_BROADCAST, "Received BROADCAST_INTENT_MSG ["
- + mQueueName + "]");
- processNextBroadcast(true);
- } break;
- case BROADCAST_TIMEOUT_MSG: {
- synchronized (mService) {
- broadcastTimeoutLocked(true);
- }
- } break;
- }
- }
- }
-
BroadcastQueue(ActivityManagerService service, Handler handler,
- String name, BroadcastConstants constants, boolean allowDelayBehindServices) {
+ String name, BroadcastConstants constants) {
mService = service;
- mHandler = new BroadcastHandler(handler.getLooper());
+ mHandler = handler;
mQueueName = name;
- mDelayBehindServices = allowDelayBehindServices;
-
mConstants = constants;
- mDispatcher = new BroadcastDispatcher(this, mConstants, mHandler, mService);
+ mSkipPolicy = new BroadcastSkipPolicy(service);
}
void start(ContentResolver resolver) {
- mDispatcher.start();
mConstants.startObserving(mHandler, resolver);
}
@@ -254,2322 +58,78 @@ public final class BroadcastQueue {
return mQueueName;
}
- public boolean isPendingBroadcastProcessLocked(int pid) {
- return mPendingBroadcast != null && mPendingBroadcast.curApp.getPid() == pid;
- }
-
- boolean isPendingBroadcastProcessLocked(ProcessRecord app) {
- return mPendingBroadcast != null && mPendingBroadcast.curApp == app;
- }
-
- public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
- r.enqueueClockTime = System.currentTimeMillis();
- r.enqueueTime = SystemClock.uptimeMillis();
- r.enqueueRealTime = SystemClock.elapsedRealtime();
- mParallelBroadcasts.add(r);
- enqueueBroadcastHelper(r);
- }
-
- public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
- r.enqueueClockTime = System.currentTimeMillis();
- r.enqueueTime = SystemClock.uptimeMillis();
- r.enqueueRealTime = SystemClock.elapsedRealtime();
- mDispatcher.enqueueOrderedBroadcastLocked(r);
- enqueueBroadcastHelper(r);
- }
+ public abstract boolean isDelayBehindServices();
- /**
- * Don't call this method directly; call enqueueParallelBroadcastLocked or
- * enqueueOrderedBroadcastLocked.
- */
- private void enqueueBroadcastHelper(BroadcastRecord r) {
- if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
- Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
- createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
- System.identityHashCode(r));
- }
- }
+ public abstract BroadcastRecord getPendingBroadcastLocked();
- /**
- * Find the same intent from queued parallel broadcast, replace with a new one and return
- * the old one.
- */
- public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) {
- return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL");
- }
+ public abstract BroadcastRecord getActiveBroadcastLocked();
/**
- * Find the same intent from queued ordered broadcast, replace with a new one and return
- * the old one.
+ * Enqueue the given broadcast to be eventually dispatched.
+ * <p>
+ * Callers must populate {@link BroadcastRecord#receivers} with the relevant
+ * targets before invoking this method.
+ * <p>
+ * When {@link Intent#FLAG_RECEIVER_REPLACE_PENDING} is set, this method
+ * internally handles replacement of any matching broadcasts.
*/
- public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) {
- return mDispatcher.replaceBroadcastLocked(r, "ORDERED");
- }
+ public abstract void enqueueBroadcastLocked(BroadcastRecord r);
- private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue,
- BroadcastRecord r, String typeForLogging) {
- final Intent intent = r.intent;
- for (int i = queue.size() - 1; i > 0; i--) {
- final BroadcastRecord old = queue.get(i);
- if (old.userId == r.userId && intent.filterEquals(old.intent)) {
- if (DEBUG_BROADCAST) {
- Slog.v(TAG_BROADCAST, "***** DROPPING "
- + typeForLogging + " [" + mQueueName + "]: " + intent);
- }
- queue.set(i, r);
- return old;
- }
- }
- return null;
- }
+ public abstract void updateUidReadyForBootCompletedBroadcastLocked(int uid);
- private final void processCurBroadcastLocked(BroadcastRecord r,
- ProcessRecord app) throws RemoteException {
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "Process cur broadcast " + r + " for app " + app);
- final IApplicationThread thread = app.getThread();
- if (thread == null) {
- throw new RemoteException();
- }
- if (app.isInFullBackup()) {
- skipReceiverLocked(r);
- return;
- }
+ public abstract boolean sendPendingBroadcastsLocked(ProcessRecord app);
- r.receiver = thread.asBinder();
- r.curApp = app;
- final ProcessReceiverRecord prr = app.mReceivers;
- prr.addCurReceiver(r);
- app.mState.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
- // Don't bump its LRU position if it's in the background restricted.
- if (mService.mInternal.getRestrictionLevel(app.info.packageName, app.userId)
- < RESTRICTION_LEVEL_RESTRICTED_BUCKET) {
- mService.updateLruProcessLocked(app, false, null);
- }
- // Make sure the oom adj score is updated before delivering the broadcast.
- // Force an update, even if there are other pending requests, overall it still saves time,
- // because time(updateOomAdj(N apps)) <= N * time(updateOomAdj(1 app)).
- mService.enqueueOomAdjTargetLocked(app);
- mService.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_RECEIVER);
+ public abstract void skipPendingBroadcastLocked(int pid);
- // Tell the application to launch this receiver.
- maybeReportBroadcastDispatchedEventLocked(r, r.curReceiver.applicationInfo.uid);
- r.intent.setComponent(r.curComponent);
+ public abstract void skipCurrentReceiverLocked(ProcessRecord app);
- boolean started = false;
- try {
- if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
- "Delivering to component " + r.curComponent
- + ": " + r);
- mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
- PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
- thread.scheduleReceiver(prepareReceiverIntent(r.intent, r.curFilteredExtras),
- r.curReceiver, null /* compatInfo (unused but need to keep method signature) */,
- r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
- app.mState.getReportedProcState());
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "Process cur broadcast " + r + " DELIVERED for app " + app);
- started = true;
- } finally {
- if (!started) {
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "Process cur broadcast " + r + ": NOT STARTED!");
- r.receiver = null;
- r.curApp = null;
- prr.removeCurReceiver(r);
- }
- }
-
- // if something bad happens here, launch the app and try again
- if (app.isKilled()) {
- throw new RemoteException("app gets killed during broadcasting");
- }
- }
+ public abstract BroadcastRecord getMatchingOrderedReceiver(IBinder receiver);
/**
- * Called by ActivityManagerService to notify that the uid has process started, if there is any
- * deferred BOOT_COMPLETED broadcast, the BroadcastDispatcher can dispatch the broadcast now.
- * @param uid
+ * Signal delivered back from a {@link BroadcastReceiver} to indicate that
+ * it's finished processing the current broadcast being dispatched to it.
+ * <p>
+ * If this signal isn't delivered back in a timely fashion, we assume the
+ * receiver has somehow wedged and we trigger an ANR.
*/
- public void updateUidReadyForBootCompletedBroadcastLocked(int uid) {
- mDispatcher.updateUidReadyForBootCompletedBroadcastLocked(uid);
- }
-
- public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
- boolean didSomething = false;
- final BroadcastRecord br = mPendingBroadcast;
- if (br != null && br.curApp.getPid() > 0 && br.curApp.getPid() == app.getPid()) {
- if (br.curApp != app) {
- Slog.e(TAG, "App mismatch when sending pending broadcast to "
- + app.processName + ", intended target is " + br.curApp.processName);
- return false;
- }
- try {
- mPendingBroadcast = null;
- br.mIsReceiverAppRunning = false;
- processCurBroadcastLocked(br, app);
- didSomething = true;
- } catch (Exception e) {
- Slog.w(TAG, "Exception in new application when starting receiver "
- + br.curComponent.flattenToShortString(), e);
- logBroadcastReceiverDiscardLocked(br);
- finishReceiverLocked(br, br.resultCode, br.resultData,
- br.resultExtras, br.resultAbort, false);
- scheduleBroadcastsLocked();
- // We need to reset the state if we failed to start the receiver.
- br.state = BroadcastRecord.IDLE;
- throw new RuntimeException(e.getMessage());
- }
- }
- return didSomething;
- }
-
- public void skipPendingBroadcastLocked(int pid) {
- final BroadcastRecord br = mPendingBroadcast;
- if (br != null && br.curApp.getPid() == pid) {
- br.state = BroadcastRecord.IDLE;
- br.nextReceiver = mPendingBroadcastRecvIndex;
- mPendingBroadcast = null;
- scheduleBroadcastsLocked();
- }
- }
+ public abstract boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
+ String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices);
- // Skip the current receiver, if any, that is in flight to the given process
- public void skipCurrentReceiverLocked(ProcessRecord app) {
- BroadcastRecord r = null;
- final BroadcastRecord curActive = mDispatcher.getActiveBroadcastLocked();
- if (curActive != null && curActive.curApp == app) {
- // confirmed: the current active broadcast is to the given app
- r = curActive;
- }
+ public abstract void backgroundServicesFinishedLocked(int userId);
- // If the current active broadcast isn't this BUT we're waiting for
- // mPendingBroadcast to spin up the target app, that's what we use.
- if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "[" + mQueueName + "] skip & discard pending app " + r);
- r = mPendingBroadcast;
- }
-
- if (r != null) {
- skipReceiverLocked(r);
- }
- }
-
- private void skipReceiverLocked(BroadcastRecord r) {
- logBroadcastReceiverDiscardLocked(r);
- finishReceiverLocked(r, r.resultCode, r.resultData,
- r.resultExtras, r.resultAbort, false);
- scheduleBroadcastsLocked();
- }
-
- public void scheduleBroadcastsLocked() {
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
- + mQueueName + "]: current="
- + mBroadcastsScheduled);
-
- if (mBroadcastsScheduled) {
- return;
- }
- mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
- mBroadcastsScheduled = true;
- }
-
- public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
- BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
- if (br != null && br.receiver == receiver) {
- return br;
- }
- return null;
- }
-
- // > 0 only, no worry about "eventual" recycling
- private int nextSplitTokenLocked() {
- int next = mNextToken + 1;
- if (next <= 0) {
- next = 1;
- }
- mNextToken = next;
- return next;
- }
-
- private void postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r) {
- // the receiver had run for less than allowed bg activity start timeout,
- // so allow the process to still start activities from bg for some more time
- String msgToken = (app.toShortString() + r.toString()).intern();
- // first, if there exists a past scheduled request to remove this token, drop
- // that request - we don't want the token to be swept from under our feet...
- mHandler.removeCallbacksAndMessages(msgToken);
- // ...then schedule the removal of the token after the extended timeout
- mHandler.postAtTime(() -> {
- synchronized (mService) {
- app.removeAllowBackgroundActivityStartsToken(r);
- }
- }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT));
- }
-
- public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
- String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
- final int state = r.state;
- final ActivityInfo receiver = r.curReceiver;
- final long finishTime = SystemClock.uptimeMillis();
- final long elapsed = finishTime - r.receiverTime;
- r.state = BroadcastRecord.IDLE;
- final int curIndex = r.nextReceiver - 1;
- if (curIndex >= 0 && curIndex < r.receivers.size() && r.curApp != null) {
- final Object curReceiver = r.receivers.get(curIndex);
- FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED, r.curApp.uid,
- r.callingUid == -1 ? Process.SYSTEM_UID : r.callingUid,
- ActivityManagerService.getShortAction(r.intent.getAction()),
- curReceiver instanceof BroadcastFilter
- ? BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME
- : BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST,
- r.mIsReceiverAppRunning
- ? BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM
- : BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD,
- r.dispatchTime - r.enqueueTime,
- r.receiverTime - r.dispatchTime,
- finishTime - r.receiverTime);
- }
- if (state == BroadcastRecord.IDLE) {
- Slog.w(TAG_BROADCAST, "finishReceiver [" + mQueueName + "] called but state is IDLE");
- }
- if (r.allowBackgroundActivityStarts && r.curApp != null) {
- if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) {
- // if the receiver has run for more than allowed bg activity start timeout,
- // just remove the token for this process now and we're done
- r.curApp.removeAllowBackgroundActivityStartsToken(r);
- } else {
- // It gets more time; post the removal to happen at the appropriate moment
- postActivityStartTokenRemoval(r.curApp, r);
- }
- }
- // If we're abandoning this broadcast before any receivers were actually spun up,
- // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply.
- if (r.nextReceiver > 0) {
- r.duration[r.nextReceiver - 1] = elapsed;
- }
-
- // if this receiver was slow, impose deferral policy on the app. This will kick in
- // when processNextBroadcastLocked() next finds this uid as a receiver identity.
- if (!r.timeoutExempt) {
- // r.curApp can be null if finish has raced with process death - benign
- // edge case, and we just ignore it because we're already cleaning up
- // as expected.
- if (r.curApp != null
- && mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) {
- // Core system packages are exempt from deferral policy
- if (!UserHandle.isCore(r.curApp.uid)) {
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST, "Broadcast receiver " + (r.nextReceiver - 1)
- + " was slow: " + receiver + " br=" + r);
- }
- mDispatcher.startDeferring(r.curApp.uid);
- } else {
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST, "Core uid " + r.curApp.uid
- + " receiver was slow but not deferring: "
- + receiver + " br=" + r);
- }
- }
- }
- } else {
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction()
- + " is exempt from deferral policy");
- }
- }
-
- r.receiver = null;
- r.intent.setComponent(null);
- if (r.curApp != null && r.curApp.mReceivers.hasCurReceiver(r)) {
- r.curApp.mReceivers.removeCurReceiver(r);
- mService.enqueueOomAdjTargetLocked(r.curApp);
- }
- if (r.curFilter != null) {
- r.curFilter.receiverList.curBroadcast = null;
- }
- r.curFilter = null;
- r.curReceiver = null;
- r.curApp = null;
- r.curFilteredExtras = null;
- mPendingBroadcast = null;
-
- r.resultCode = resultCode;
- r.resultData = resultData;
- r.resultExtras = resultExtras;
- if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
- r.resultAbort = resultAbort;
- } else {
- r.resultAbort = false;
- }
-
- // If we want to wait behind services *AND* we're finishing the head/
- // active broadcast on its queue
- if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
- && r.queue.mDispatcher.getActiveBroadcastLocked() == r) {
- ActivityInfo nextReceiver;
- if (r.nextReceiver < r.receivers.size()) {
- Object obj = r.receivers.get(r.nextReceiver);
- nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
- } else {
- nextReceiver = null;
- }
- // Don't do this if the next receive is in the same process as the current one.
- if (receiver == null || nextReceiver == null
- || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
- || !receiver.processName.equals(nextReceiver.processName)) {
- // In this case, we are ready to process the next receiver for the current broadcast,
- // but are on a queue that would like to wait for services to finish before moving
- // on. If there are background services currently starting, then we will go into a
- // special state where we hold off on continuing this broadcast until they are done.
- if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
- Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
- r.state = BroadcastRecord.WAITING_SERVICES;
- return false;
- }
- }
- }
-
- r.curComponent = null;
-
- // We will process the next receiver right now if this is finishing
- // an app receiver (which is always asynchronous) or after we have
- // come back from calling a receiver.
- return state == BroadcastRecord.APP_RECEIVE
- || state == BroadcastRecord.CALL_DONE_RECEIVE;
- }
-
- public void backgroundServicesFinishedLocked(int userId) {
- BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
- if (br != null) {
- if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
- Slog.i(TAG, "Resuming delayed broadcast");
- br.curComponent = null;
- br.state = BroadcastRecord.IDLE;
- processNextBroadcastLocked(false, false);
- }
- }
- }
-
- void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
- Intent intent, int resultCode, String data, Bundle extras,
- boolean ordered, boolean sticky, int sendingUser,
- int receiverUid, int callingUid, long dispatchDelay,
- long receiveDelay) throws RemoteException {
- // Send the intent to the receiver asynchronously using one-way binder calls.
- if (app != null) {
- final IApplicationThread thread = app.getThread();
- if (thread != null) {
- // If we have an app thread, do the call through that so it is
- // correctly ordered with other one-way calls.
- try {
- thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
- data, extras, ordered, sticky, sendingUser,
- app.mState.getReportedProcState());
- // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
- // DeadObjectException when the process isn't actually dead.
- //} catch (DeadObjectException ex) {
- // Failed to call into the process. It's dying so just let it die and move on.
- // throw ex;
- } catch (RemoteException ex) {
- // Failed to call into the process. It's either dying or wedged. Kill it gently.
- synchronized (mService) {
- Slog.w(TAG, "Can't deliver broadcast to " + app.processName
- + " (pid " + app.getPid() + "). Crashing it.");
- app.scheduleCrashLocked("can't deliver broadcast",
- CannotDeliverBroadcastException.TYPE_ID, /* extras=*/ null);
- }
- throw ex;
- }
- } else {
- // Application has died. Receiver doesn't exist.
- throw new RemoteException("app.thread must not be null");
- }
- } else {
- receiver.performReceive(intent, resultCode, data, extras, ordered,
- sticky, sendingUser);
- }
- if (!ordered) {
- FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED,
- receiverUid == -1 ? Process.SYSTEM_UID : receiverUid,
- callingUid == -1 ? Process.SYSTEM_UID : callingUid,
- ActivityManagerService.getShortAction(intent.getAction()),
- BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME,
- BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM,
- dispatchDelay, receiveDelay, 0 /* finish_delay */);
- }
- }
-
- private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
- BroadcastFilter filter, boolean ordered, int index) {
- boolean skip = false;
- if (r.options != null && !r.options.testRequireCompatChange(filter.owningUid)) {
- Slog.w(TAG, "Compat change filtered: broadcasting " + r.intent.toString()
- + " to uid " + filter.owningUid + " due to compat change "
- + r.options.getRequireCompatChangeId());
- skip = true;
- }
- if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
- filter.packageName, filter.owningUid)) {
- Slog.w(TAG, "Association not allowed: broadcasting "
- + r.intent.toString()
- + " from " + r.callerPackage + " (pid=" + r.callingPid
- + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
- + filter);
- skip = true;
- }
- if (!skip && !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
- r.callingPid, r.resolvedType, filter.receiverList.uid)) {
- Slog.w(TAG, "Firewall blocked: broadcasting "
- + r.intent.toString()
- + " from " + r.callerPackage + " (pid=" + r.callingPid
- + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
- + filter);
- skip = true;
- }
- // Check that the sender has permission to send to this receiver
- if (filter.requiredPermission != null) {
- int perm = mService.checkComponentPermission(filter.requiredPermission,
- r.callingPid, r.callingUid, -1, true);
- if (perm != PackageManager.PERMISSION_GRANTED) {
- Slog.w(TAG, "Permission Denial: broadcasting "
- + r.intent.toString()
- + " from " + r.callerPackage + " (pid="
- + r.callingPid + ", uid=" + r.callingUid + ")"
- + " requires " + filter.requiredPermission
- + " due to registered receiver " + filter);
- skip = true;
- } else {
- final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
- if (opCode != AppOpsManager.OP_NONE
- && mService.getAppOpsManager().noteOpNoThrow(opCode, r.callingUid,
- r.callerPackage, r.callerFeatureId, "Broadcast sent to protected receiver")
- != AppOpsManager.MODE_ALLOWED) {
- Slog.w(TAG, "Appop Denial: broadcasting "
- + r.intent.toString()
- + " from " + r.callerPackage + " (pid="
- + r.callingPid + ", uid=" + r.callingUid + ")"
- + " requires appop " + AppOpsManager.permissionToOp(
- filter.requiredPermission)
- + " due to registered receiver " + filter);
- skip = true;
- }
- }
- }
-
- if (!skip && (filter.receiverList.app == null || filter.receiverList.app.isKilled()
- || filter.receiverList.app.mErrorState.isCrashing())) {
- Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
- + " to " + filter.receiverList + ": process gone or crashing");
- skip = true;
- }
-
- // Ensure that broadcasts are only sent to other Instant Apps if they are marked as
- // visible to Instant Apps.
- final boolean visibleToInstantApps =
- (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
-
- if (!skip && !visibleToInstantApps && filter.instantApp
- && filter.receiverList.uid != r.callingUid) {
- Slog.w(TAG, "Instant App Denial: receiving "
- + r.intent.toString()
- + " to " + filter.receiverList.app
- + " (pid=" + filter.receiverList.pid
- + ", uid=" + filter.receiverList.uid + ")"
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")"
- + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS");
- skip = true;
- }
-
- if (!skip && !filter.visibleToInstantApp && r.callerInstantApp
- && filter.receiverList.uid != r.callingUid) {
- Slog.w(TAG, "Instant App Denial: receiving "
- + r.intent.toString()
- + " to " + filter.receiverList.app
- + " (pid=" + filter.receiverList.pid
- + ", uid=" + filter.receiverList.uid + ")"
- + " requires receiver be visible to instant apps"
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- }
-
- // Check that the receiver has the required permission(s) to receive this broadcast.
- if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
- for (int i = 0; i < r.requiredPermissions.length; i++) {
- String requiredPermission = r.requiredPermissions[i];
- int perm = mService.checkComponentPermission(requiredPermission,
- filter.receiverList.pid, filter.receiverList.uid, -1, true);
- if (perm != PackageManager.PERMISSION_GRANTED) {
- Slog.w(TAG, "Permission Denial: receiving "
- + r.intent.toString()
- + " to " + filter.receiverList.app
- + " (pid=" + filter.receiverList.pid
- + ", uid=" + filter.receiverList.uid + ")"
- + " requires " + requiredPermission
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- break;
- }
- int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
- if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
- && mService.getAppOpsManager().noteOpNoThrow(appOp,
- filter.receiverList.uid, filter.packageName, filter.featureId,
- "Broadcast delivered to registered receiver " + filter.receiverId)
- != AppOpsManager.MODE_ALLOWED) {
- Slog.w(TAG, "Appop Denial: receiving "
- + r.intent.toString()
- + " to " + filter.receiverList.app
- + " (pid=" + filter.receiverList.pid
- + ", uid=" + filter.receiverList.uid + ")"
- + " requires appop " + AppOpsManager.permissionToOp(
- requiredPermission)
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- break;
- }
- }
- }
- if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
- int perm = mService.checkComponentPermission(null,
- filter.receiverList.pid, filter.receiverList.uid, -1, true);
- if (perm != PackageManager.PERMISSION_GRANTED) {
- Slog.w(TAG, "Permission Denial: security check failed when receiving "
- + r.intent.toString()
- + " to " + filter.receiverList.app
- + " (pid=" + filter.receiverList.pid
- + ", uid=" + filter.receiverList.uid + ")"
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- }
- }
- // Check that the receiver does *not* have any excluded permissions
- if (!skip && r.excludedPermissions != null && r.excludedPermissions.length > 0) {
- for (int i = 0; i < r.excludedPermissions.length; i++) {
- String excludedPermission = r.excludedPermissions[i];
- final int perm = mService.checkComponentPermission(excludedPermission,
- filter.receiverList.pid, filter.receiverList.uid, -1, true);
-
- int appOp = AppOpsManager.permissionToOpCode(excludedPermission);
- if (appOp != AppOpsManager.OP_NONE) {
- // When there is an app op associated with the permission,
- // skip when both the permission and the app op are
- // granted.
- if ((perm == PackageManager.PERMISSION_GRANTED) && (
- mService.getAppOpsManager().checkOpNoThrow(appOp,
- filter.receiverList.uid,
- filter.packageName)
- == AppOpsManager.MODE_ALLOWED)) {
- Slog.w(TAG, "Appop Denial: receiving "
- + r.intent.toString()
- + " to " + filter.receiverList.app
- + " (pid=" + filter.receiverList.pid
- + ", uid=" + filter.receiverList.uid + ")"
- + " excludes appop " + AppOpsManager.permissionToOp(
- excludedPermission)
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- break;
- }
- } else {
- // When there is no app op associated with the permission,
- // skip when permission is granted.
- if (perm == PackageManager.PERMISSION_GRANTED) {
- Slog.w(TAG, "Permission Denial: receiving "
- + r.intent.toString()
- + " to " + filter.receiverList.app
- + " (pid=" + filter.receiverList.pid
- + ", uid=" + filter.receiverList.uid + ")"
- + " excludes " + excludedPermission
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- break;
- }
- }
- }
- }
-
- // Check that the receiver does *not* belong to any of the excluded packages
- if (!skip && r.excludedPackages != null && r.excludedPackages.length > 0) {
- if (ArrayUtils.contains(r.excludedPackages, filter.packageName)) {
- Slog.w(TAG, "Skipping delivery of excluded package "
- + r.intent.toString()
- + " to " + filter.receiverList.app
- + " (pid=" + filter.receiverList.pid
- + ", uid=" + filter.receiverList.uid + ")"
- + " excludes package " + filter.packageName
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- }
- }
-
- // If the broadcast also requires an app op check that as well.
- if (!skip && r.appOp != AppOpsManager.OP_NONE
- && mService.getAppOpsManager().noteOpNoThrow(r.appOp,
- filter.receiverList.uid, filter.packageName, filter.featureId,
- "Broadcast delivered to registered receiver " + filter.receiverId)
- != AppOpsManager.MODE_ALLOWED) {
- Slog.w(TAG, "Appop Denial: receiving "
- + r.intent.toString()
- + " to " + filter.receiverList.app
- + " (pid=" + filter.receiverList.pid
- + ", uid=" + filter.receiverList.uid + ")"
- + " requires appop " + AppOpsManager.opToName(r.appOp)
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- }
-
- // Ensure that broadcasts are only sent to other apps if they are explicitly marked as
- // exported, or are System level broadcasts
- if (!skip && !filter.exported && mService.checkComponentPermission(null, r.callingPid,
- r.callingUid, filter.receiverList.uid, filter.exported)
- != PackageManager.PERMISSION_GRANTED) {
- Slog.w(TAG, "Exported Denial: sending "
- + r.intent.toString()
- + ", action: " + r.intent.getAction()
- + " from " + r.callerPackage
- + " (uid=" + r.callingUid + ")"
- + " due to receiver " + filter.receiverList.app
- + " (uid " + filter.receiverList.uid + ")"
- + " not specifying RECEIVER_EXPORTED");
- skip = true;
- }
-
- // Filter packages in the intent extras, skipping delivery if none of the packages is
- // visible to the receiver.
- Bundle filteredExtras = null;
- if (!skip && r.filterExtrasForReceiver != null) {
- final Bundle extras = r.intent.getExtras();
- if (extras != null) {
- filteredExtras = r.filterExtrasForReceiver.apply(filter.receiverList.uid, extras);
- if (filteredExtras == null) {
- if (DEBUG_BROADCAST) {
- Slog.v(TAG, "Skipping delivery to "
- + filter.receiverList.app
- + " : receiver is filtered by the package visibility");
- }
- skip = true;
- }
- }
- }
-
- if (skip) {
- r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
- return;
- }
-
- // If permissions need a review before any of the app components can run, we drop
- // the broadcast and if the calling app is in the foreground and the broadcast is
- // explicit we launch the review UI passing it a pending intent to send the skipped
- // broadcast.
- if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
- filter.owningUserId)) {
- r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
- return;
- }
-
- r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
-
- // If this is not being sent as an ordered broadcast, then we
- // don't want to touch the fields that keep track of the current
- // state of ordered broadcasts.
- if (ordered) {
- r.receiver = filter.receiverList.receiver.asBinder();
- r.curFilter = filter;
- filter.receiverList.curBroadcast = r;
- r.state = BroadcastRecord.CALL_IN_RECEIVE;
- if (filter.receiverList.app != null) {
- // Bump hosting application to no longer be in background
- // scheduling class. Note that we can't do that if there
- // isn't an app... but we can only be in that case for
- // things that directly call the IActivityManager API, which
- // are already core system stuff so don't matter for this.
- r.curApp = filter.receiverList.app;
- filter.receiverList.app.mReceivers.addCurReceiver(r);
- mService.enqueueOomAdjTargetLocked(r.curApp);
- mService.updateOomAdjPendingTargetsLocked(
- OOM_ADJ_REASON_START_RECEIVER);
- }
- } else if (filter.receiverList.app != null) {
- mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(filter.receiverList.app,
- OOM_ADJ_REASON_START_RECEIVER);
- }
-
- try {
- if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
- "Delivering to " + filter + " : " + r);
- if (filter.receiverList.app != null && filter.receiverList.app.isInFullBackup()) {
- // Skip delivery if full backup in progress
- // If it's an ordered broadcast, we need to continue to the next receiver.
- if (ordered) {
- skipReceiverLocked(r);
- }
- } else {
- r.receiverTime = SystemClock.uptimeMillis();
- maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
- maybeScheduleTempAllowlistLocked(filter.owningUid, r, r.options);
- maybeReportBroadcastDispatchedEventLocked(r, filter.owningUid);
- performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
- prepareReceiverIntent(r.intent, filteredExtras), r.resultCode, r.resultData,
- r.resultExtras, r.ordered, r.initialSticky, r.userId,
- filter.receiverList.uid, r.callingUid,
- r.dispatchTime - r.enqueueTime,
- r.receiverTime - r.dispatchTime);
- // parallel broadcasts are fire-and-forget, not bookended by a call to
- // finishReceiverLocked(), so we manage their activity-start token here
- if (filter.receiverList.app != null
- && r.allowBackgroundActivityStarts && !r.ordered) {
- postActivityStartTokenRemoval(filter.receiverList.app, r);
- }
- }
- if (ordered) {
- r.state = BroadcastRecord.CALL_DONE_RECEIVE;
- }
- } catch (RemoteException e) {
- Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
- // Clean up ProcessRecord state related to this broadcast attempt
- if (filter.receiverList.app != null) {
- filter.receiverList.app.removeAllowBackgroundActivityStartsToken(r);
- if (ordered) {
- filter.receiverList.app.mReceivers.removeCurReceiver(r);
- // Something wrong, its oom adj could be downgraded, but not in a hurry.
- mService.enqueueOomAdjTargetLocked(r.curApp);
- }
- }
- // And BroadcastRecord state related to ordered delivery, if appropriate
- if (ordered) {
- r.receiver = null;
- r.curFilter = null;
- filter.receiverList.curBroadcast = null;
- }
- }
- }
-
- private boolean requestStartTargetPermissionsReviewIfNeededLocked(
- BroadcastRecord receiverRecord, String receivingPackageName,
- final int receivingUserId) {
- if (!mService.getPackageManagerInternal().isPermissionsReviewRequired(
- receivingPackageName, receivingUserId)) {
- return true;
- }
-
- final boolean callerForeground = receiverRecord.callerApp != null
- ? receiverRecord.callerApp.mState.getSetSchedGroup()
- != ProcessList.SCHED_GROUP_BACKGROUND : true;
-
- // Show a permission review UI only for explicit broadcast from a foreground app
- if (callerForeground && receiverRecord.intent.getComponent() != null) {
- IIntentSender target = mService.mPendingIntentController.getIntentSender(
- ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
- receiverRecord.callerFeatureId, receiverRecord.callingUid,
- receiverRecord.userId, null, null, 0,
- new Intent[]{receiverRecord.intent},
- new String[]{receiverRecord.intent.resolveType(mService.mContext
- .getContentResolver())},
- PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
- | PendingIntent.FLAG_IMMUTABLE, null);
-
- final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
- | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
- | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
- intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
- intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
-
- if (DEBUG_PERMISSIONS_REVIEW) {
- Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
- + receivingPackageName);
- }
-
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
- }
- });
- } else {
- Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
- + receivingPackageName + " requires a permissions review");
- }
-
- return false;
- }
-
- void maybeScheduleTempAllowlistLocked(int uid, BroadcastRecord r,
- @Nullable BroadcastOptions brOptions) {
- if (brOptions == null || brOptions.getTemporaryAppAllowlistDuration() <= 0) {
- return;
- }
- long duration = brOptions.getTemporaryAppAllowlistDuration();
- final @TempAllowListType int type = brOptions.getTemporaryAppAllowlistType();
- final @ReasonCode int reasonCode = brOptions.getTemporaryAppAllowlistReasonCode();
- final String reason = brOptions.getTemporaryAppAllowlistReason();
-
- if (duration > Integer.MAX_VALUE) {
- duration = Integer.MAX_VALUE;
- }
- // XXX ideally we should pause the broadcast until everything behind this is done,
- // or else we will likely start dispatching the broadcast before we have opened
- // access to the app (there is a lot of asynchronicity behind this). It is probably
- // not that big a deal, however, because the main purpose here is to allow apps
- // to hold wake locks, and they will be able to acquire their wake lock immediately
- // it just won't be enabled until we get through this work.
- StringBuilder b = new StringBuilder();
- b.append("broadcast:");
- UserHandle.formatUid(b, r.callingUid);
- b.append(":");
- if (r.intent.getAction() != null) {
- b.append(r.intent.getAction());
- } else if (r.intent.getComponent() != null) {
- r.intent.getComponent().appendShortString(b);
- } else if (r.intent.getData() != null) {
- b.append(r.intent.getData());
- }
- b.append(",reason:");
- b.append(reason);
- if (DEBUG_BROADCAST) {
- Slog.v(TAG, "Broadcast temp allowlist uid=" + uid + " duration=" + duration
- + " type=" + type + " : " + b.toString());
- }
- mService.tempAllowlistUidLocked(uid, duration, reasonCode, b.toString(), type,
- r.callingUid);
- }
+ public abstract void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj);
/**
- * Return true if all given permissions are signature-only perms.
+ * Signal from OS internals that the given package (or some subset of that
+ * package) has been disabled or uninstalled, and that any pending
+ * broadcasts should be cleaned up.
*/
- final boolean isSignaturePerm(String[] perms) {
- if (perms == null) {
- return false;
- }
- IPermissionManager pm = AppGlobals.getPermissionManager();
- for (int i = perms.length-1; i >= 0; i--) {
- try {
- PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
- if (pi == null) {
- // a required permission that no package has actually
- // defined cannot be signature-required.
- return false;
- }
- if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
- | PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
- != PermissionInfo.PROTECTION_SIGNATURE) {
- // If this a signature permission and NOT allowed for privileged apps, it
- // is okay... otherwise, nope!
- return false;
- }
- } catch (RemoteException e) {
- return false;
- }
- }
- return true;
- }
-
- private void processNextBroadcast(boolean fromMsg) {
- synchronized (mService) {
- processNextBroadcastLocked(fromMsg, false);
- }
- }
+ public abstract boolean cleanupDisabledPackageReceiversLocked(
+ String packageName, Set<String> filterByClasses, int userId, boolean doit);
- static String broadcastDescription(BroadcastRecord r, ComponentName component) {
- return r.intent.toString()
- + " from " + r.callerPackage + " (pid=" + r.callingPid
- + ", uid=" + r.callingUid + ") to " + component.flattenToShortString();
- }
-
- private static Intent prepareReceiverIntent(@NonNull Intent originalIntent,
- @Nullable Bundle filteredExtras) {
- final Intent intent = new Intent(originalIntent);
- if (filteredExtras != null) {
- intent.replaceExtras(filteredExtras);
- }
- return intent;
- }
-
- final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
- BroadcastRecord r;
-
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
- + mQueueName + "]: "
- + mParallelBroadcasts.size() + " parallel broadcasts; "
- + mDispatcher.describeStateLocked());
-
- mService.updateCpuStats();
-
- if (fromMsg) {
- mBroadcastsScheduled = false;
- }
-
- // First, deliver any non-serialized broadcasts right away.
- while (mParallelBroadcasts.size() > 0) {
- r = mParallelBroadcasts.remove(0);
- r.dispatchTime = SystemClock.uptimeMillis();
- r.dispatchRealTime = SystemClock.elapsedRealtime();
- r.dispatchClockTime = System.currentTimeMillis();
- r.mIsReceiverAppRunning = true;
-
- if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
- Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
- createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
- System.identityHashCode(r));
- Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
- createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
- System.identityHashCode(r));
- }
-
- final int N = r.receivers.size();
- if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
- + mQueueName + "] " + r);
- for (int i=0; i<N; i++) {
- Object target = r.receivers.get(i);
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "Delivering non-ordered on [" + mQueueName + "] to registered "
- + target + ": " + r);
- deliverToRegisteredReceiverLocked(r,
- (BroadcastFilter) target, false, i);
- }
- addBroadcastToHistoryLocked(r);
- if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
- + mQueueName + "] " + r);
- }
-
- // Now take care of the next serialized one...
-
- // If we are waiting for a process to come up to handle the next
- // broadcast, then do nothing at this point. Just in case, we
- // check that the process we're waiting for still exists.
- if (mPendingBroadcast != null) {
- if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
- "processNextBroadcast [" + mQueueName + "]: waiting for "
- + mPendingBroadcast.curApp);
-
- boolean isDead;
- if (mPendingBroadcast.curApp.getPid() > 0) {
- synchronized (mService.mPidsSelfLocked) {
- ProcessRecord proc = mService.mPidsSelfLocked.get(
- mPendingBroadcast.curApp.getPid());
- isDead = proc == null || proc.mErrorState.isCrashing();
- }
- } else {
- final ProcessRecord proc = mService.mProcessList.getProcessNamesLOSP().get(
- mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid);
- isDead = proc == null || !proc.isPendingStart();
- }
- if (!isDead) {
- // It's still alive, so keep waiting
- return;
- } else {
- Slog.w(TAG, "pending app ["
- + mQueueName + "]" + mPendingBroadcast.curApp
- + " died before responding to broadcast");
- mPendingBroadcast.state = BroadcastRecord.IDLE;
- mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
- mPendingBroadcast = null;
- }
- }
-
- boolean looped = false;
-
- do {
- final long now = SystemClock.uptimeMillis();
- r = mDispatcher.getNextBroadcastLocked(now);
-
- if (r == null) {
- // No more broadcasts are deliverable right now, so all done!
- mDispatcher.scheduleDeferralCheckLocked(false);
- synchronized (mService.mAppProfiler.mProfilerLock) {
- mService.mAppProfiler.scheduleAppGcsLPf();
- }
- if (looped && !skipOomAdj) {
- // If we had finished the last ordered broadcast, then
- // make sure all processes have correct oom and sched
- // adjustments.
- mService.updateOomAdjPendingTargetsLocked(
- OOM_ADJ_REASON_START_RECEIVER);
- }
-
- // when we have no more ordered broadcast on this queue, stop logging
- if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) {
- mLogLatencyMetrics = false;
- }
-
- return;
- }
-
- boolean forceReceive = false;
-
- // Ensure that even if something goes awry with the timeout
- // detection, we catch "hung" broadcasts here, discard them,
- // and continue to make progress.
- //
- // This is only done if the system is ready so that early-stage receivers
- // don't get executed with timeouts; and of course other timeout-
- // exempt broadcasts are ignored.
- int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
- if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
- if ((numReceivers > 0) &&
- (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) {
- Slog.w(TAG, "Hung broadcast ["
- + mQueueName + "] discarded after timeout failure:"
- + " now=" + now
- + " dispatchTime=" + r.dispatchTime
- + " startTime=" + r.receiverTime
- + " intent=" + r.intent
- + " numReceivers=" + numReceivers
- + " nextReceiver=" + r.nextReceiver
- + " state=" + r.state);
- broadcastTimeoutLocked(false); // forcibly finish this broadcast
- forceReceive = true;
- r.state = BroadcastRecord.IDLE;
- }
- }
-
- if (r.state != BroadcastRecord.IDLE) {
- if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
- "processNextBroadcast("
- + mQueueName + ") called when not idle (state="
- + r.state + ")");
- return;
- }
-
- // Is the current broadcast is done for any reason?
- if (r.receivers == null || r.nextReceiver >= numReceivers
- || r.resultAbort || forceReceive) {
- // Send the final result if requested
- if (r.resultTo != null) {
- boolean sendResult = true;
-
- // if this was part of a split/deferral complex, update the refcount and only
- // send the completion when we clear all of them
- if (r.splitToken != 0) {
- int newCount = mSplitRefcounts.get(r.splitToken) - 1;
- if (newCount == 0) {
- // done! clear out this record's bookkeeping and deliver
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST,
- "Sending broadcast completion for split token "
- + r.splitToken + " : " + r.intent.getAction());
- }
- mSplitRefcounts.delete(r.splitToken);
- } else {
- // still have some split broadcast records in flight; update refcount
- // and hold off on the callback
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST,
- "Result refcount now " + newCount + " for split token "
- + r.splitToken + " : " + r.intent.getAction()
- + " - not sending completion yet");
- }
- sendResult = false;
- mSplitRefcounts.put(r.splitToken, newCount);
- }
- }
- if (sendResult) {
- if (r.callerApp != null) {
- mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(
- r.callerApp, OOM_ADJ_REASON_FINISH_RECEIVER);
- }
- try {
- if (DEBUG_BROADCAST) {
- Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] "
- + r.intent.getAction() + " app=" + r.callerApp);
- }
- if (r.dispatchTime == 0) {
- // The dispatch time here could be 0, in case it's a parallel
- // broadcast but it has a result receiver. Set it to now.
- r.dispatchTime = now;
- }
- r.mIsReceiverAppRunning = true;
- performReceiveLocked(r.callerApp, r.resultTo,
- new Intent(r.intent), r.resultCode,
- r.resultData, r.resultExtras, false, false, r.userId,
- r.callingUid, r.callingUid,
- r.dispatchTime - r.enqueueTime,
- now - r.dispatchTime);
- logBootCompletedBroadcastCompletionLatencyIfPossible(r);
- // Set this to null so that the reference
- // (local and remote) isn't kept in the mBroadcastHistory.
- r.resultTo = null;
- } catch (RemoteException e) {
- r.resultTo = null;
- Slog.w(TAG, "Failure ["
- + mQueueName + "] sending broadcast result of "
- + r.intent, e);
- }
- }
- }
-
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
- cancelBroadcastTimeoutLocked();
-
- if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
- "Finished with ordered broadcast " + r);
-
- // ... and on to the next...
- addBroadcastToHistoryLocked(r);
- if (r.intent.getComponent() == null && r.intent.getPackage() == null
- && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
- // This was an implicit broadcast... let's record it for posterity.
- mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
- r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
- }
- mDispatcher.retireBroadcastLocked(r);
- r = null;
- looped = true;
- continue;
- }
-
- // Check whether the next receiver is under deferral policy, and handle that
- // accordingly. If the current broadcast was already part of deferred-delivery
- // tracking, we know that it must now be deliverable as-is without re-deferral.
- if (!r.deferred) {
- final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver));
- if (mDispatcher.isDeferringLocked(receiverUid)) {
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid
- + " at " + r.nextReceiver + " is under deferral");
- }
- // If this is the only (remaining) receiver in the broadcast, "splitting"
- // doesn't make sense -- just defer it as-is and retire it as the
- // currently active outgoing broadcast.
- BroadcastRecord defer;
- if (r.nextReceiver + 1 == numReceivers) {
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST, "Sole receiver of " + r
- + " is under deferral; setting aside and proceeding");
- }
- defer = r;
- mDispatcher.retireBroadcastLocked(r);
- } else {
- // Nontrivial case; split out 'uid's receivers to a new broadcast record
- // and defer that, then loop and pick up continuing delivery of the current
- // record (now absent those receivers).
-
- // The split operation is guaranteed to match at least at 'nextReceiver'
- defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver);
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST, "Post split:");
- Slog.i(TAG_BROADCAST, "Original broadcast receivers:");
- for (int i = 0; i < r.receivers.size(); i++) {
- Slog.i(TAG_BROADCAST, " " + r.receivers.get(i));
- }
- Slog.i(TAG_BROADCAST, "Split receivers:");
- for (int i = 0; i < defer.receivers.size(); i++) {
- Slog.i(TAG_BROADCAST, " " + defer.receivers.get(i));
- }
- }
- // Track completion refcount as well if relevant
- if (r.resultTo != null) {
- int token = r.splitToken;
- if (token == 0) {
- // first split of this record; refcount for 'r' and 'deferred'
- r.splitToken = defer.splitToken = nextSplitTokenLocked();
- mSplitRefcounts.put(r.splitToken, 2);
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST,
- "Broadcast needs split refcount; using new token "
- + r.splitToken);
- }
- } else {
- // new split from an already-refcounted situation; increment count
- final int curCount = mSplitRefcounts.get(token);
- if (DEBUG_BROADCAST_DEFERRAL) {
- if (curCount == 0) {
- Slog.wtf(TAG_BROADCAST,
- "Split refcount is zero with token for " + r);
- }
- }
- mSplitRefcounts.put(token, curCount + 1);
- if (DEBUG_BROADCAST_DEFERRAL) {
- Slog.i(TAG_BROADCAST, "New split count for token " + token
- + " is " + (curCount + 1));
- }
- }
- }
- }
- mDispatcher.addDeferredBroadcast(receiverUid, defer);
- r = null;
- looped = true;
- continue;
- }
- }
- } while (r == null);
-
- // Get the next receiver...
- int recIdx = r.nextReceiver++;
-
- // Keep track of when this receiver started, and make sure there
- // is a timeout message pending to kill it if need be.
- r.receiverTime = SystemClock.uptimeMillis();
- if (recIdx == 0) {
- r.dispatchTime = r.receiverTime;
- r.dispatchRealTime = SystemClock.elapsedRealtime();
- r.dispatchClockTime = System.currentTimeMillis();
-
- if (mLogLatencyMetrics) {
- FrameworkStatsLog.write(
- FrameworkStatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED,
- r.dispatchClockTime - r.enqueueClockTime);
- }
-
- if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
- Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
- createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
- System.identityHashCode(r));
- Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
- createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
- System.identityHashCode(r));
- }
- if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
- + mQueueName + "] " + r);
- }
- if (! mPendingBroadcastTimeoutMessage) {
- long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "Submitting BROADCAST_TIMEOUT_MSG ["
- + mQueueName + "] for " + r + " at " + timeoutTime);
- setBroadcastTimeoutLocked(timeoutTime);
- }
-
- final BroadcastOptions brOptions = r.options;
- final Object nextReceiver = r.receivers.get(recIdx);
-
- if (nextReceiver instanceof BroadcastFilter) {
- // Simple case: this is a registered receiver who gets
- // a direct call.
- BroadcastFilter filter = (BroadcastFilter)nextReceiver;
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "Delivering ordered ["
- + mQueueName + "] to registered "
- + filter + ": " + r);
- r.mIsReceiverAppRunning = true;
- deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
- if (r.receiver == null || !r.ordered) {
- // The receiver has already finished, so schedule to
- // process the next one.
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
- + mQueueName + "]: ordered="
- + r.ordered + " receiver=" + r.receiver);
- r.state = BroadcastRecord.IDLE;
- scheduleBroadcastsLocked();
- } else {
- if (filter.receiverList != null) {
- maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
- // r is guaranteed ordered at this point, so we know finishReceiverLocked()
- // will get a callback and handle the activity start token lifecycle.
- }
- }
- return;
- }
-
- // Hard case: need to instantiate the receiver, possibly
- // starting its application process to host it.
-
- ResolveInfo info =
- (ResolveInfo)nextReceiver;
- ComponentName component = new ComponentName(
- info.activityInfo.applicationInfo.packageName,
- info.activityInfo.name);
-
- boolean skip = false;
- if (brOptions != null &&
- (info.activityInfo.applicationInfo.targetSdkVersion
- < brOptions.getMinManifestReceiverApiLevel() ||
- info.activityInfo.applicationInfo.targetSdkVersion
- > brOptions.getMaxManifestReceiverApiLevel())) {
- Slog.w(TAG, "Target SDK mismatch: receiver " + info.activityInfo
- + " targets " + info.activityInfo.applicationInfo.targetSdkVersion
- + " but delivery restricted to ["
- + brOptions.getMinManifestReceiverApiLevel() + ", "
- + brOptions.getMaxManifestReceiverApiLevel()
- + "] broadcasting " + broadcastDescription(r, component));
- skip = true;
- }
- if (brOptions != null &&
- !brOptions.testRequireCompatChange(info.activityInfo.applicationInfo.uid)) {
- Slog.w(TAG, "Compat change filtered: broadcasting " + broadcastDescription(r, component)
- + " to uid " + info.activityInfo.applicationInfo.uid + " due to compat change "
- + r.options.getRequireCompatChangeId());
- skip = true;
- }
- if (!skip && !mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
- component.getPackageName(), info.activityInfo.applicationInfo.uid)) {
- Slog.w(TAG, "Association not allowed: broadcasting "
- + broadcastDescription(r, component));
- skip = true;
- }
- if (!skip) {
- skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
- r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
- if (skip) {
- Slog.w(TAG, "Firewall blocked: broadcasting "
- + broadcastDescription(r, component));
- }
- }
- int perm = mService.checkComponentPermission(info.activityInfo.permission,
- r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
- info.activityInfo.exported);
- if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
- if (!info.activityInfo.exported) {
- Slog.w(TAG, "Permission Denial: broadcasting "
- + broadcastDescription(r, component)
- + " is not exported from uid " + info.activityInfo.applicationInfo.uid);
- } else {
- Slog.w(TAG, "Permission Denial: broadcasting "
- + broadcastDescription(r, component)
- + " requires " + info.activityInfo.permission);
- }
- skip = true;
- } else if (!skip && info.activityInfo.permission != null) {
- final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
- if (opCode != AppOpsManager.OP_NONE && mService.getAppOpsManager().noteOpNoThrow(opCode,
- r.callingUid, r.callerPackage, r.callerFeatureId,
- "Broadcast delivered to " + info.activityInfo.name)
- != AppOpsManager.MODE_ALLOWED) {
- Slog.w(TAG, "Appop Denial: broadcasting "
- + broadcastDescription(r, component)
- + " requires appop " + AppOpsManager.permissionToOp(
- info.activityInfo.permission));
- skip = true;
- }
- }
-
- boolean isSingleton = false;
- try {
- isSingleton = mService.isSingleton(info.activityInfo.processName,
- info.activityInfo.applicationInfo,
- info.activityInfo.name, info.activityInfo.flags);
- } catch (SecurityException e) {
- Slog.w(TAG, e.getMessage());
- skip = true;
- }
- if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
- if (ActivityManager.checkUidPermission(
- android.Manifest.permission.INTERACT_ACROSS_USERS,
- info.activityInfo.applicationInfo.uid)
- != PackageManager.PERMISSION_GRANTED) {
- Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
- + " requests FLAG_SINGLE_USER, but app does not hold "
- + android.Manifest.permission.INTERACT_ACROSS_USERS);
- skip = true;
- }
- }
- if (!skip && info.activityInfo.applicationInfo.isInstantApp()
- && r.callingUid != info.activityInfo.applicationInfo.uid) {
- Slog.w(TAG, "Instant App Denial: receiving "
- + r.intent
- + " to " + component.flattenToShortString()
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")"
- + " Instant Apps do not support manifest receivers");
- skip = true;
- }
- if (!skip && r.callerInstantApp
- && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
- && r.callingUid != info.activityInfo.applicationInfo.uid) {
- Slog.w(TAG, "Instant App Denial: receiving "
- + r.intent
- + " to " + component.flattenToShortString()
- + " requires receiver have visibleToInstantApps set"
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- }
- if (r.curApp != null && r.curApp.mErrorState.isCrashing()) {
- // If the target process is crashing, just skip it.
- Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
- + " to " + r.curApp + ": process crashing");
- skip = true;
- }
- if (!skip) {
- boolean isAvailable = false;
- try {
- isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
- info.activityInfo.packageName,
- UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
- } catch (Exception e) {
- // all such failures mean we skip this receiver
- Slog.w(TAG, "Exception getting recipient info for "
- + info.activityInfo.packageName, e);
- }
- if (!isAvailable) {
- Slog.w(TAG_BROADCAST,
- "Skipping delivery to " + info.activityInfo.packageName + " / "
- + info.activityInfo.applicationInfo.uid
- + " : package no longer available");
- skip = true;
- }
- }
-
- // If permissions need a review before any of the app components can run, we drop
- // the broadcast and if the calling app is in the foreground and the broadcast is
- // explicit we launch the review UI passing it a pending intent to send the skipped
- // broadcast.
- if (!skip) {
- if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
- info.activityInfo.packageName, UserHandle.getUserId(
- info.activityInfo.applicationInfo.uid))) {
- Slog.w(TAG_BROADCAST,
- "Skipping delivery: permission review required for "
- + broadcastDescription(r, component));
- skip = true;
- }
- }
-
- // This is safe to do even if we are skipping the broadcast, and we need
- // this information now to evaluate whether it is going to be allowed to run.
- final int receiverUid = info.activityInfo.applicationInfo.uid;
- // If it's a singleton, it needs to be the same app or a special app
- if (r.callingUid != Process.SYSTEM_UID && isSingleton
- && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
- info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
- }
- String targetProcess = info.activityInfo.processName;
- ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
- info.activityInfo.applicationInfo.uid);
-
- if (!skip) {
- final int allowed = mService.getAppStartModeLOSP(
- info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
- info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
- if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
- // We won't allow this receiver to be launched if the app has been
- // completely disabled from launches, or it was not explicitly sent
- // to it and the app is in a state that should not receive it
- // (depending on how getAppStartModeLOSP has determined that).
- if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
- Slog.w(TAG, "Background execution disabled: receiving "
- + r.intent + " to "
- + component.flattenToShortString());
- skip = true;
- } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
- || (r.intent.getComponent() == null
- && r.intent.getPackage() == null
- && ((r.intent.getFlags()
- & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
- && !isSignaturePerm(r.requiredPermissions))) {
- mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
- component.getPackageName());
- Slog.w(TAG, "Background execution not allowed: receiving "
- + r.intent + " to "
- + component.flattenToShortString());
- skip = true;
- }
- }
- }
-
- if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction())
- && !mService.mUserController
- .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid),
- 0 /* flags */)) {
- skip = true;
- Slog.w(TAG,
- "Skipping delivery to " + info.activityInfo.packageName + " / "
- + info.activityInfo.applicationInfo.uid + " : user is not running");
- }
-
- if (!skip && r.excludedPermissions != null && r.excludedPermissions.length > 0) {
- for (int i = 0; i < r.excludedPermissions.length; i++) {
- String excludedPermission = r.excludedPermissions[i];
- try {
- perm = AppGlobals.getPackageManager()
- .checkPermission(excludedPermission,
- info.activityInfo.applicationInfo.packageName,
- UserHandle
- .getUserId(info.activityInfo.applicationInfo.uid));
- } catch (RemoteException e) {
- perm = PackageManager.PERMISSION_DENIED;
- }
-
- int appOp = AppOpsManager.permissionToOpCode(excludedPermission);
- if (appOp != AppOpsManager.OP_NONE) {
- // When there is an app op associated with the permission,
- // skip when both the permission and the app op are
- // granted.
- if ((perm == PackageManager.PERMISSION_GRANTED) && (
- mService.getAppOpsManager().checkOpNoThrow(appOp,
- info.activityInfo.applicationInfo.uid,
- info.activityInfo.packageName)
- == AppOpsManager.MODE_ALLOWED)) {
- skip = true;
- break;
- }
- } else {
- // When there is no app op associated with the permission,
- // skip when permission is granted.
- if (perm == PackageManager.PERMISSION_GRANTED) {
- skip = true;
- break;
- }
- }
- }
- }
-
- // Check that the receiver does *not* belong to any of the excluded packages
- if (!skip && r.excludedPackages != null && r.excludedPackages.length > 0) {
- if (ArrayUtils.contains(r.excludedPackages, component.getPackageName())) {
- Slog.w(TAG, "Skipping delivery of excluded package "
- + r.intent + " to "
- + component.flattenToShortString()
- + " excludes package " + component.getPackageName()
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- }
- }
-
- if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
- r.requiredPermissions != null && r.requiredPermissions.length > 0) {
- for (int i = 0; i < r.requiredPermissions.length; i++) {
- String requiredPermission = r.requiredPermissions[i];
- try {
- perm = AppGlobals.getPackageManager().
- checkPermission(requiredPermission,
- info.activityInfo.applicationInfo.packageName,
- UserHandle
- .getUserId(info.activityInfo.applicationInfo.uid));
- } catch (RemoteException e) {
- perm = PackageManager.PERMISSION_DENIED;
- }
- if (perm != PackageManager.PERMISSION_GRANTED) {
- Slog.w(TAG, "Permission Denial: receiving "
- + r.intent + " to "
- + component.flattenToShortString()
- + " requires " + requiredPermission
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- skip = true;
- break;
- }
- int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
- if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp) {
- if (!noteOpForManifestReceiver(appOp, r, info, component)) {
- skip = true;
- break;
- }
- }
- }
- }
- if (!skip && r.appOp != AppOpsManager.OP_NONE) {
- if (!noteOpForManifestReceiver(r.appOp, r, info, component)) {
- skip = true;
- }
- }
-
- // Filter packages in the intent extras, skipping delivery if none of the packages is
- // visible to the receiver.
- Bundle filteredExtras = null;
- if (!skip && r.filterExtrasForReceiver != null) {
- final Bundle extras = r.intent.getExtras();
- if (extras != null) {
- filteredExtras = r.filterExtrasForReceiver.apply(receiverUid, extras);
- if (filteredExtras == null) {
- if (DEBUG_BROADCAST) {
- Slog.v(TAG, "Skipping delivery to "
- + info.activityInfo.packageName + " / " + receiverUid
- + " : receiver is filtered by the package visibility");
- }
- skip = true;
- }
- }
- }
-
- if (skip) {
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "Skipping delivery of ordered [" + mQueueName + "] "
- + r + " for reason described above");
- r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
- r.receiver = null;
- r.curFilter = null;
- r.state = BroadcastRecord.IDLE;
- r.manifestSkipCount++;
- scheduleBroadcastsLocked();
- return;
- }
- r.manifestCount++;
-
- r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
- r.state = BroadcastRecord.APP_RECEIVE;
- r.curComponent = component;
- r.curReceiver = info.activityInfo;
- r.curFilteredExtras = filteredExtras;
- if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
- Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
- + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
- + receiverUid);
- }
- final boolean isActivityCapable =
- (brOptions != null && brOptions.getTemporaryAppAllowlistDuration() > 0);
- maybeScheduleTempAllowlistLocked(receiverUid, r, brOptions);
-
- // Report that a component is used for explicit broadcasts.
- if (r.intent.getComponent() != null && r.curComponent != null
- && !TextUtils.equals(r.curComponent.getPackageName(), r.callerPackage)) {
- mService.mUsageStatsService.reportEvent(
- r.curComponent.getPackageName(), r.userId, Event.APP_COMPONENT_USED);
- }
-
- // Broadcast is being executed, its package can't be stopped.
- try {
- AppGlobals.getPackageManager().setPackageStoppedState(
- r.curComponent.getPackageName(), false, r.userId);
- } catch (RemoteException e) {
- } catch (IllegalArgumentException e) {
- Slog.w(TAG, "Failed trying to unstop package "
- + r.curComponent.getPackageName() + ": " + e);
- }
-
- // Is this receiver's application already running?
- if (app != null && app.getThread() != null && !app.isKilled()) {
- try {
- app.addPackage(info.activityInfo.packageName,
- info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats);
- maybeAddAllowBackgroundActivityStartsToken(app, r);
- r.mIsReceiverAppRunning = true;
- processCurBroadcastLocked(r, app);
- return;
- } catch (RemoteException e) {
- Slog.w(TAG, "Exception when sending broadcast to "
- + r.curComponent, e);
- } catch (RuntimeException e) {
- Slog.wtf(TAG, "Failed sending broadcast to "
- + r.curComponent + " with " + r.intent, e);
- // If some unexpected exception happened, just skip
- // this broadcast. At this point we are not in the call
- // from a client, so throwing an exception out from here
- // will crash the entire system instead of just whoever
- // sent the broadcast.
- logBroadcastReceiverDiscardLocked(r);
- finishReceiverLocked(r, r.resultCode, r.resultData,
- r.resultExtras, r.resultAbort, false);
- scheduleBroadcastsLocked();
- // We need to reset the state if we failed to start the receiver.
- r.state = BroadcastRecord.IDLE;
- return;
- }
-
- // If a dead object exception was thrown -- fall through to
- // restart the application.
- }
-
- // Not running -- get it started, to be executed when the app comes up.
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "Need to start app ["
- + mQueueName + "] " + targetProcess + " for broadcast " + r);
- r.curApp = mService.startProcessLocked(targetProcess,
- info.activityInfo.applicationInfo, true,
- r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
- new HostingRecord(HostingRecord.HOSTING_TYPE_BROADCAST, r.curComponent,
- r.intent.getAction(), getHostingRecordTriggerType(r)),
- isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY,
- (r.intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false);
- if (r.curApp == null) {
- // Ah, this recipient is unavailable. Finish it if necessary,
- // and mark the broadcast record as ready for the next.
- Slog.w(TAG, "Unable to launch app "
- + info.activityInfo.applicationInfo.packageName + "/"
- + receiverUid + " for broadcast "
- + r.intent + ": process is bad");
- logBroadcastReceiverDiscardLocked(r);
- finishReceiverLocked(r, r.resultCode, r.resultData,
- r.resultExtras, r.resultAbort, false);
- scheduleBroadcastsLocked();
- r.state = BroadcastRecord.IDLE;
- return;
- }
-
- maybeAddAllowBackgroundActivityStartsToken(r.curApp, r);
- mPendingBroadcast = r;
- mPendingBroadcastRecvIndex = recIdx;
- }
-
- private String getHostingRecordTriggerType(BroadcastRecord r) {
- if (r.alarm) {
- return HostingRecord.TRIGGER_TYPE_ALARM;
- } else if (r.pushMessage) {
- return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE;
- } else if (r.pushMessageOverQuota) {
- return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE_OVER_QUOTA;
- }
- return HostingRecord.TRIGGER_TYPE_UNKNOWN;
- }
-
- @Nullable
- private String getTargetPackage(BroadcastRecord r) {
- if (r.intent == null) {
- return null;
- }
- if (r.intent.getPackage() != null) {
- return r.intent.getPackage();
- } else if (r.intent.getComponent() != null) {
- return r.intent.getComponent().getPackageName();
- }
- return null;
- }
-
- private void logBootCompletedBroadcastCompletionLatencyIfPossible(BroadcastRecord r) {
- // Only log after last receiver.
- // In case of split BOOT_COMPLETED broadcast, make sure only call this method on the
- // last BroadcastRecord of the split broadcast which has non-null resultTo.
- final int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
- if (r.nextReceiver < numReceivers) {
- return;
- }
- final String action = r.intent.getAction();
- int event = 0;
- if (Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action)) {
- event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED;
- } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
- event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED;
- }
- if (event != 0) {
- final int dispatchLatency = (int)(r.dispatchTime - r.enqueueTime);
- final int completeLatency = (int)
- (SystemClock.uptimeMillis() - r.enqueueTime);
- final int dispatchRealLatency = (int)(r.dispatchRealTime - r.enqueueRealTime);
- final int completeRealLatency = (int)
- (SystemClock.elapsedRealtime() - r.enqueueRealTime);
- int userType = FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__TYPE_UNKNOWN;
- // This method is called very infrequently, no performance issue we call
- // LocalServices.getService() here.
- final UserManagerInternal umInternal = LocalServices.getService(
- UserManagerInternal.class);
- final UserInfo userInfo = umInternal.getUserInfo(r.userId);
- if (userInfo != null) {
- userType = UserManager.getUserTypeForStatsd(userInfo.userType);
- }
- Slog.i(TAG_BROADCAST,
- "BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED action:"
- + action
- + " dispatchLatency:" + dispatchLatency
- + " completeLatency:" + completeLatency
- + " dispatchRealLatency:" + dispatchRealLatency
- + " completeRealLatency:" + completeRealLatency
- + " receiversSize:" + numReceivers
- + " userId:" + r.userId
- + " userType:" + (userInfo != null? userInfo.userType : null));
- FrameworkStatsLog.write(
- BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED,
- event,
- dispatchLatency,
- completeLatency,
- dispatchRealLatency,
- completeRealLatency,
- r.userId,
- userType);
- }
- }
-
- private void maybeReportBroadcastDispatchedEventLocked(BroadcastRecord r, int targetUid) {
- if (r.options == null || r.options.getIdForResponseEvent() <= 0) {
- return;
- }
- final String targetPackage = getTargetPackage(r);
- // Ignore non-explicit broadcasts
- if (targetPackage == null) {
- return;
- }
- getUsageStatsManagerInternal().reportBroadcastDispatched(
- r.callingUid, targetPackage, UserHandle.of(r.userId),
- r.options.getIdForResponseEvent(), SystemClock.elapsedRealtime(),
- mService.getUidStateLocked(targetUid));
- }
-
- @NonNull
- private UsageStatsManagerInternal getUsageStatsManagerInternal() {
- final UsageStatsManagerInternal usageStatsManagerInternal =
- LocalServices.getService(UsageStatsManagerInternal.class);
- return usageStatsManagerInternal;
- }
-
- private boolean noteOpForManifestReceiver(int appOp, BroadcastRecord r, ResolveInfo info,
- ComponentName component) {
- if (ArrayUtils.isEmpty(info.activityInfo.attributionTags)) {
- return noteOpForManifestReceiverInner(appOp, r, info, component, null);
- } else {
- // Attribution tags provided, noteOp each tag
- for (String tag : info.activityInfo.attributionTags) {
- if (!noteOpForManifestReceiverInner(appOp, r, info, component, tag)) {
- return false;
- }
- }
- return true;
- }
- }
-
- private boolean noteOpForManifestReceiverInner(int appOp, BroadcastRecord r, ResolveInfo info,
- ComponentName component, String tag) {
- if (mService.getAppOpsManager().noteOpNoThrow(appOp,
- info.activityInfo.applicationInfo.uid,
- info.activityInfo.packageName,
- tag,
- "Broadcast delivered to " + info.activityInfo.name)
- != AppOpsManager.MODE_ALLOWED) {
- Slog.w(TAG, "Appop Denial: receiving "
- + r.intent + " to "
- + component.flattenToShortString()
- + " requires appop " + AppOpsManager.opToName(appOp)
- + " due to sender " + r.callerPackage
- + " (uid " + r.callingUid + ")");
- return false;
- }
- return true;
- }
-
- private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) {
- if (r == null || proc == null || !r.allowBackgroundActivityStarts) {
- return;
- }
- String msgToken = (proc.toShortString() + r.toString()).intern();
- // first, if there exists a past scheduled request to remove this token, drop
- // that request - we don't want the token to be swept from under our feet...
- mHandler.removeCallbacksAndMessages(msgToken);
- // ...then add the token
- proc.addOrUpdateAllowBackgroundActivityStartsToken(r, r.mBackgroundActivityStartsToken);
- }
-
- final void setBroadcastTimeoutLocked(long timeoutTime) {
- if (! mPendingBroadcastTimeoutMessage) {
- Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
- mHandler.sendMessageAtTime(msg, timeoutTime);
- mPendingBroadcastTimeoutMessage = true;
- }
- }
-
- final void cancelBroadcastTimeoutLocked() {
- if (mPendingBroadcastTimeoutMessage) {
- mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
- mPendingBroadcastTimeoutMessage = false;
- }
- }
-
- final void broadcastTimeoutLocked(boolean fromMsg) {
- if (fromMsg) {
- mPendingBroadcastTimeoutMessage = false;
- }
-
- if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) {
- return;
- }
-
- long now = SystemClock.uptimeMillis();
- BroadcastRecord r = mDispatcher.getActiveBroadcastLocked();
- if (fromMsg) {
- if (!mService.mProcessesReady) {
- // Only process broadcast timeouts if the system is ready; some early
- // broadcasts do heavy work setting up system facilities
- return;
- }
-
- // If the broadcast is generally exempt from timeout tracking, we're done
- if (r.timeoutExempt) {
- if (DEBUG_BROADCAST) {
- Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: "
- + r.intent.getAction());
- }
- return;
- }
-
- long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
- if (timeoutTime > now) {
- // We can observe premature timeouts because we do not cancel and reset the
- // broadcast timeout message after each receiver finishes. Instead, we set up
- // an initial timeout then kick it down the road a little further as needed
- // when it expires.
- if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
- "Premature timeout ["
- + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
- + timeoutTime);
- setBroadcastTimeoutLocked(timeoutTime);
- return;
- }
- }
-
- if (r.state == BroadcastRecord.WAITING_SERVICES) {
- // In this case the broadcast had already finished, but we had decided to wait
- // for started services to finish as well before going on. So if we have actually
- // waited long enough time timeout the broadcast, let's give up on the whole thing
- // and just move on to the next.
- Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null
- ? r.curComponent.flattenToShortString() : "(null)"));
- r.curComponent = null;
- r.state = BroadcastRecord.IDLE;
- processNextBroadcastLocked(false, false);
- return;
- }
-
- // If the receiver app is being debugged we quietly ignore unresponsiveness, just
- // tidying up and moving on to the next broadcast without crashing or ANRing this
- // app just because it's stopped at a breakpoint.
- final boolean debugging = (r.curApp != null && r.curApp.isDebugging());
-
- long timeoutDurationMs = now - r.receiverTime;
- Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
- + ", started " + timeoutDurationMs + "ms ago");
- r.receiverTime = now;
- if (!debugging) {
- r.anrCount++;
- }
-
- ProcessRecord app = null;
- TimeoutRecord timeoutRecord = null;
-
- Object curReceiver;
- if (r.nextReceiver > 0) {
- curReceiver = r.receivers.get(r.nextReceiver-1);
- r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
- } else {
- curReceiver = r.curReceiver;
- }
- Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
- logBroadcastReceiverDiscardLocked(r);
- if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
- BroadcastFilter bf = (BroadcastFilter)curReceiver;
- if (bf.receiverList.pid != 0
- && bf.receiverList.pid != ActivityManagerService.MY_PID) {
- synchronized (mService.mPidsSelfLocked) {
- app = mService.mPidsSelfLocked.get(
- bf.receiverList.pid);
- }
- }
- } else {
- app = r.curApp;
- }
-
- if (app != null) {
- String anrMessage =
- "Broadcast of " + r.intent.toString() + ", waited " + timeoutDurationMs
- + "ms";
- timeoutRecord = TimeoutRecord.forBroadcastReceiver(anrMessage);
- }
-
- if (mPendingBroadcast == r) {
- mPendingBroadcast = null;
- }
-
- // Move on to the next receiver.
- finishReceiverLocked(r, r.resultCode, r.resultData,
- r.resultExtras, r.resultAbort, false);
- scheduleBroadcastsLocked();
-
- if (!debugging && timeoutRecord != null) {
- mService.mAnrHelper.appNotResponding(app, timeoutRecord);
- }
- }
-
- private final int ringAdvance(int x, final int increment, final int ringSize) {
- x += increment;
- if (x < 0) return (ringSize - 1);
- else if (x >= ringSize) return 0;
- else return x;
- }
-
- private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
- if (original.callingUid < 0) {
- // This was from a registerReceiver() call; ignore it.
- return;
- }
- original.finishTime = SystemClock.uptimeMillis();
-
- if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
- Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
- createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
- System.identityHashCode(original));
- }
-
- final ApplicationInfo info = original.callerApp != null ? original.callerApp.info : null;
- final String callerPackage = info != null ? info.packageName : original.callerPackage;
- if (callerPackage != null) {
- mService.mHandler.obtainMessage(ActivityManagerService.DISPATCH_SENDING_BROADCAST_EVENT,
- original.callingUid, 0, callerPackage).sendToTarget();
- }
-
- // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords,
- // So don't change the incoming record directly.
- final BroadcastRecord historyRecord = original.maybeStripForHistory();
-
- mBroadcastHistory[mHistoryNext] = historyRecord;
- mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
-
- mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent;
- mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime;
- mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime;
- mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
- mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
- }
-
- boolean cleanupDisabledPackageReceiversLocked(
- String packageName, Set<String> filterByClasses, int userId, boolean doit) {
- boolean didSomething = false;
- for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
- didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
- packageName, filterByClasses, userId, doit);
- if (!doit && didSomething) {
- return true;
- }
- }
-
- didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName,
- filterByClasses, userId, doit);
-
- return didSomething;
- }
-
- final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
- final int logIndex = r.nextReceiver - 1;
- if (logIndex >= 0 && logIndex < r.receivers.size()) {
- Object curReceiver = r.receivers.get(logIndex);
- if (curReceiver instanceof BroadcastFilter) {
- BroadcastFilter bf = (BroadcastFilter) curReceiver;
- EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
- bf.owningUserId, System.identityHashCode(r),
- r.intent.getAction(), logIndex, System.identityHashCode(bf));
- } else {
- ResolveInfo ri = (ResolveInfo) curReceiver;
- EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
- UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
- System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
- }
- } else {
- if (logIndex < 0) Slog.w(TAG,
- "Discarding broadcast before first receiver is invoked: " + r);
- EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
- -1, System.identityHashCode(r),
- r.intent.getAction(),
- r.nextReceiver,
- "NONE");
- }
- }
-
- private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
- return formatSimple("Broadcast %s from %s (%s) %s",
- state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
- record.callerPackage == null ? "" : record.callerPackage,
- record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
- record.intent == null ? "" : record.intent.getAction());
- }
-
- boolean isIdle() {
- return mParallelBroadcasts.isEmpty() && mDispatcher.isIdle()
- && (mPendingBroadcast == null);
- }
-
- // Used by wait-for-broadcast-idle : fast-forward all current deferrals to
- // be immediately deliverable.
- void cancelDeferrals() {
- synchronized (mService) {
- mDispatcher.cancelDeferralsLocked();
- scheduleBroadcastsLocked();
- }
- }
-
- String describeState() {
- synchronized (mService) {
- return mParallelBroadcasts.size() + " parallel; "
- + mDispatcher.describeStateLocked();
- }
- }
-
- void dumpDebug(ProtoOutputStream proto, long fieldId) {
- long token = proto.start(fieldId);
- proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
- int N;
- N = mParallelBroadcasts.size();
- for (int i = N - 1; i >= 0; i--) {
- mParallelBroadcasts.get(i).dumpDebug(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
- }
- mDispatcher.dumpDebug(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
- if (mPendingBroadcast != null) {
- mPendingBroadcast.dumpDebug(proto, BroadcastQueueProto.PENDING_BROADCAST);
- }
-
- int lastIndex = mHistoryNext;
- int ringIndex = lastIndex;
- do {
- // increasing index = more recent entry, and we want to print the most
- // recent first and work backwards, so we roll through the ring backwards.
- ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
- BroadcastRecord r = mBroadcastHistory[ringIndex];
- if (r != null) {
- r.dumpDebug(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS);
- }
- } while (ringIndex != lastIndex);
-
- lastIndex = ringIndex = mSummaryHistoryNext;
- do {
- ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
- Intent intent = mBroadcastSummaryHistory[ringIndex];
- if (intent == null) {
- continue;
- }
- long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY);
- intent.dumpDebug(proto, BroadcastQueueProto.BroadcastSummary.INTENT,
- false, true, true, false);
- proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS,
- mSummaryHistoryEnqueueTime[ringIndex]);
- proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS,
- mSummaryHistoryDispatchTime[ringIndex]);
- proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS,
- mSummaryHistoryFinishTime[ringIndex]);
- proto.end(summaryToken);
- } while (ringIndex != lastIndex);
- proto.end(token);
- }
-
- final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
- int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
- if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty()
- || mPendingBroadcast != null) {
- boolean printed = false;
- for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
- BroadcastRecord br = mParallelBroadcasts.get(i);
- if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
- continue;
- }
- if (!printed) {
- if (needSep) {
- pw.println();
- }
- needSep = true;
- printed = true;
- pw.println(" Active broadcasts [" + mQueueName + "]:");
- }
- pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
- br.dump(pw, " ", sdf);
- }
-
- mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf);
-
- if (dumpPackage == null || (mPendingBroadcast != null
- && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
- pw.println();
- pw.println(" Pending broadcast [" + mQueueName + "]:");
- if (mPendingBroadcast != null) {
- mPendingBroadcast.dump(pw, " ", sdf);
- } else {
- pw.println(" (null)");
- }
- needSep = true;
- }
- }
-
- mConstants.dump(pw);
-
- int i;
- boolean printed = false;
+ /**
+ * Quickly determine if this queue has broadcasts that are still waiting to
+ * be delivered at some point in the future.
+ *
+ * @see #flush()
+ */
+ public abstract boolean isIdle();
- i = -1;
- int lastIndex = mHistoryNext;
- int ringIndex = lastIndex;
- do {
- // increasing index = more recent entry, and we want to print the most
- // recent first and work backwards, so we roll through the ring backwards.
- ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
- BroadcastRecord r = mBroadcastHistory[ringIndex];
- if (r == null) {
- continue;
- }
+ /**
+ * Brief summary of internal state, useful for debugging purposes.
+ */
+ public abstract String describeState();
- i++; // genuine record of some sort even if we're filtering it out
- if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
- continue;
- }
- if (!printed) {
- if (needSep) {
- pw.println();
- }
- needSep = true;
- pw.println(" Historical broadcasts [" + mQueueName + "]:");
- printed = true;
- }
- if (dumpAll) {
- pw.print(" Historical Broadcast " + mQueueName + " #");
- pw.print(i); pw.println(":");
- r.dump(pw, " ", sdf);
- } else {
- pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
- pw.print(" ");
- pw.println(r.intent.toShortString(false, true, true, false));
- if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
- pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
- }
- Bundle bundle = r.intent.getExtras();
- if (bundle != null) {
- pw.print(" extras: "); pw.println(bundle.toString());
- }
- }
- } while (ringIndex != lastIndex);
+ /**
+ * Flush any broadcasts still waiting to be delivered, causing them to be
+ * delivered as soon as possible.
+ *
+ * @see #isIdle()
+ */
+ public abstract void flush();
- if (dumpPackage == null) {
- lastIndex = ringIndex = mSummaryHistoryNext;
- if (dumpAll) {
- printed = false;
- i = -1;
- } else {
- // roll over the 'i' full dumps that have already been issued
- for (int j = i;
- j > 0 && ringIndex != lastIndex;) {
- ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
- BroadcastRecord r = mBroadcastHistory[ringIndex];
- if (r == null) {
- continue;
- }
- j--;
- }
- }
- // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
- // the overall broadcast history.
- do {
- ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
- Intent intent = mBroadcastSummaryHistory[ringIndex];
- if (intent == null) {
- continue;
- }
- if (!printed) {
- if (needSep) {
- pw.println();
- }
- needSep = true;
- pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
- printed = true;
- }
- if (!dumpAll && i >= 50) {
- pw.println(" ...");
- break;
- }
- i++;
- pw.print(" #"); pw.print(i); pw.print(": ");
- pw.println(intent.toShortString(false, true, true, false));
- pw.print(" ");
- TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
- - mSummaryHistoryEnqueueTime[ringIndex], pw);
- pw.print(" dispatch ");
- TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
- - mSummaryHistoryDispatchTime[ringIndex], pw);
- pw.println(" finish");
- pw.print(" enq=");
- pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
- pw.print(" disp=");
- pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
- pw.print(" fin=");
- pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
- Bundle bundle = intent.getExtras();
- if (bundle != null) {
- pw.print(" extras: "); pw.println(bundle.toString());
- }
- } while (ringIndex != lastIndex);
- }
+ public abstract void dumpDebug(ProtoOutputStream proto, long fieldId);
- return needSep;
- }
+ public abstract boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
+ int opti, boolean dumpAll, String dumpPackage, boolean needSep);
}
diff --git a/services/core/java/com/android/server/am/BroadcastQueueImpl.java b/services/core/java/com/android/server/am/BroadcastQueueImpl.java
new file mode 100644
index 000000000000..4bffe351a379
--- /dev/null
+++ b/services/core/java/com/android/server/am/BroadcastQueueImpl.java
@@ -0,0 +1,1960 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.am;
+
+import static android.app.ActivityManager.RESTRICTION_LEVEL_RESTRICTED_BUCKET;
+import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
+import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
+import static android.text.TextUtils.formatSimple;
+
+import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED;
+import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED;
+import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED;
+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;
+import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM;
+import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST;
+import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME;
+import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
+import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_DEFERRAL;
+import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT;
+import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
+import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
+import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
+import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER;
+import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_START_RECEIVER;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.Activity;
+import android.app.ActivityManager;
+import android.app.AppGlobals;
+import android.app.BroadcastOptions;
+import android.app.IApplicationThread;
+import android.app.RemoteServiceException.CannotDeliverBroadcastException;
+import android.app.usage.UsageEvents.Event;
+import android.app.usage.UsageStatsManagerInternal;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.IIntentReceiver;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.pm.UserInfo;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Message;
+import android.os.PowerExemptionManager.ReasonCode;
+import android.os.PowerExemptionManager.TempAllowListType;
+import android.os.Process;
+import android.os.RemoteException;
+import android.os.SystemClock;
+import android.os.Trace;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.text.TextUtils;
+import android.util.EventLog;
+import android.util.Slog;
+import android.util.SparseIntArray;
+import android.util.TimeUtils;
+import android.util.proto.ProtoOutputStream;
+
+import com.android.internal.os.TimeoutRecord;
+import com.android.internal.util.FrameworkStatsLog;
+import com.android.server.LocalServices;
+import com.android.server.pm.UserManagerInternal;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Set;
+
+/**
+ * BROADCASTS
+ *
+ * We keep three broadcast queues and associated bookkeeping, one for those at
+ * foreground priority, and one for normal (background-priority) broadcasts, and one to
+ * offload special broadcasts that we know take a long time, such as BOOT_COMPLETED.
+ */
+public class BroadcastQueueImpl extends BroadcastQueue {
+ private static final String TAG_MU = TAG + POSTFIX_MU;
+ private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
+
+ static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
+ static final int MAX_BROADCAST_SUMMARY_HISTORY
+ = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
+
+ /**
+ * If true, we can delay broadcasts while waiting services to finish in the previous
+ * receiver's process.
+ */
+ final boolean mDelayBehindServices;
+
+ /**
+ * Lists of all active broadcasts that are to be executed immediately
+ * (without waiting for another broadcast to finish). Currently this only
+ * contains broadcasts to registered receivers, to avoid spinning up
+ * a bunch of processes to execute IntentReceiver components. Background-
+ * and foreground-priority broadcasts are queued separately.
+ */
+ final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
+
+ /**
+ * Tracking of the ordered broadcast queue, including deferral policy and alarm
+ * prioritization.
+ */
+ final BroadcastDispatcher mDispatcher;
+
+ /**
+ * Refcounting for completion callbacks of split/deferred broadcasts. The key
+ * is an opaque integer token assigned lazily when a broadcast is first split
+ * into multiple BroadcastRecord objects.
+ */
+ final SparseIntArray mSplitRefcounts = new SparseIntArray();
+ private int mNextToken = 0;
+
+ /**
+ * Historical data of past broadcasts, for debugging. This is a ring buffer
+ * whose last element is at mHistoryNext.
+ */
+ final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
+ int mHistoryNext = 0;
+
+ /**
+ * Summary of historical data of past broadcasts, for debugging. This is a
+ * ring buffer whose last element is at mSummaryHistoryNext.
+ */
+ final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
+ int mSummaryHistoryNext = 0;
+
+ /**
+ * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
+ * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
+ * clock time, not elapsed.
+ */
+ final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
+ final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
+ final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
+
+ /**
+ * Set when we current have a BROADCAST_INTENT_MSG in flight.
+ */
+ boolean mBroadcastsScheduled = false;
+
+ /**
+ * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
+ */
+ boolean mPendingBroadcastTimeoutMessage;
+
+ /**
+ * Intent broadcasts that we have tried to start, but are
+ * waiting for the application's process to be created. We only
+ * need one per scheduling class (instead of a list) because we always
+ * process broadcasts one at a time, so no others can be started while
+ * waiting for this one.
+ */
+ BroadcastRecord mPendingBroadcast = null;
+
+ /**
+ * The receiver index that is pending, to restart the broadcast if needed.
+ */
+ int mPendingBroadcastRecvIndex;
+
+ static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
+ static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
+
+ // log latency metrics for ordered broadcasts during BOOT_COMPLETED processing
+ boolean mLogLatencyMetrics = true;
+
+ final BroadcastHandler mHandler;
+
+ private final class BroadcastHandler extends Handler {
+ public BroadcastHandler(Looper looper) {
+ super(looper, null, true);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case BROADCAST_INTENT_MSG: {
+ if (DEBUG_BROADCAST) Slog.v(
+ TAG_BROADCAST, "Received BROADCAST_INTENT_MSG ["
+ + mQueueName + "]");
+ processNextBroadcast(true);
+ } break;
+ case BROADCAST_TIMEOUT_MSG: {
+ synchronized (mService) {
+ broadcastTimeoutLocked(true);
+ }
+ } break;
+ }
+ }
+ }
+
+ BroadcastQueueImpl(ActivityManagerService service, Handler handler,
+ String name, BroadcastConstants constants, boolean allowDelayBehindServices) {
+ super(service, handler, name, constants);
+ mHandler = new BroadcastHandler(handler.getLooper());
+ mDelayBehindServices = allowDelayBehindServices;
+ mDispatcher = new BroadcastDispatcher(this, mConstants, mHandler, mService);
+ }
+
+ void start(ContentResolver resolver) {
+ mDispatcher.start();
+ mConstants.startObserving(mHandler, resolver);
+ }
+
+ public boolean isDelayBehindServices() {
+ return mDelayBehindServices;
+ }
+
+ public BroadcastRecord getPendingBroadcastLocked() {
+ return mPendingBroadcast;
+ }
+
+ public BroadcastRecord getActiveBroadcastLocked() {
+ return mDispatcher.getActiveBroadcastLocked();
+ }
+
+ public void enqueueBroadcastLocked(BroadcastRecord r) {
+ final boolean replacePending = (r.intent.getFlags()
+ & Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
+
+ // Ordered broadcasts obviously need to be dispatched in serial order,
+ // but this implementation expects all manifest receivers to also be
+ // dispatched in a serial fashion
+ boolean serialDispatch = r.ordered;
+ if (!serialDispatch) {
+ final int N = (r.receivers != null) ? r.receivers.size() : 0;
+ for (int i = 0; i < N; i++) {
+ if (r.receivers.get(i) instanceof ResolveInfo) {
+ serialDispatch = true;
+ break;
+ }
+ }
+ }
+
+ if (serialDispatch) {
+ final BroadcastRecord oldRecord =
+ replacePending ? replaceOrderedBroadcastLocked(r) : null;
+ if (oldRecord != null) {
+ // Replaced, fire the result-to receiver.
+ if (oldRecord.resultTo != null) {
+ try {
+ oldRecord.mIsReceiverAppRunning = true;
+ performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
+ oldRecord.intent,
+ Activity.RESULT_CANCELED, null, null,
+ false, false, oldRecord.userId, oldRecord.callingUid, r.callingUid,
+ SystemClock.uptimeMillis() - oldRecord.enqueueTime, 0);
+ } catch (RemoteException e) {
+ Slog.w(TAG, "Failure ["
+ + mQueueName + "] sending broadcast result of "
+ + oldRecord.intent, e);
+
+ }
+ }
+ } else {
+ enqueueOrderedBroadcastLocked(r);
+ scheduleBroadcastsLocked();
+ }
+ } else {
+ final boolean replaced = replacePending
+ && (replaceParallelBroadcastLocked(r) != null);
+ // Note: We assume resultTo is null for non-ordered broadcasts.
+ if (!replaced) {
+ enqueueParallelBroadcastLocked(r);
+ scheduleBroadcastsLocked();
+ }
+ }
+ }
+
+ public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
+ r.enqueueClockTime = System.currentTimeMillis();
+ r.enqueueTime = SystemClock.uptimeMillis();
+ r.enqueueRealTime = SystemClock.elapsedRealtime();
+ mParallelBroadcasts.add(r);
+ enqueueBroadcastHelper(r);
+ }
+
+ public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
+ r.enqueueClockTime = System.currentTimeMillis();
+ r.enqueueTime = SystemClock.uptimeMillis();
+ r.enqueueRealTime = SystemClock.elapsedRealtime();
+ mDispatcher.enqueueOrderedBroadcastLocked(r);
+ enqueueBroadcastHelper(r);
+ }
+
+ /**
+ * Don't call this method directly; call enqueueParallelBroadcastLocked or
+ * enqueueOrderedBroadcastLocked.
+ */
+ private void enqueueBroadcastHelper(BroadcastRecord r) {
+ if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
+ Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
+ createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
+ System.identityHashCode(r));
+ }
+ }
+
+ /**
+ * Find the same intent from queued parallel broadcast, replace with a new one and return
+ * the old one.
+ */
+ public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) {
+ return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL");
+ }
+
+ /**
+ * Find the same intent from queued ordered broadcast, replace with a new one and return
+ * the old one.
+ */
+ public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) {
+ return mDispatcher.replaceBroadcastLocked(r, "ORDERED");
+ }
+
+ private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue,
+ BroadcastRecord r, String typeForLogging) {
+ final Intent intent = r.intent;
+ for (int i = queue.size() - 1; i > 0; i--) {
+ final BroadcastRecord old = queue.get(i);
+ if (old.userId == r.userId && intent.filterEquals(old.intent)) {
+ if (DEBUG_BROADCAST) {
+ Slog.v(TAG_BROADCAST, "***** DROPPING "
+ + typeForLogging + " [" + mQueueName + "]: " + intent);
+ }
+ queue.set(i, r);
+ return old;
+ }
+ }
+ return null;
+ }
+
+ private final void processCurBroadcastLocked(BroadcastRecord r,
+ ProcessRecord app) throws RemoteException {
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "Process cur broadcast " + r + " for app " + app);
+ final IApplicationThread thread = app.getThread();
+ if (thread == null) {
+ throw new RemoteException();
+ }
+ if (app.isInFullBackup()) {
+ skipReceiverLocked(r);
+ return;
+ }
+
+ r.receiver = thread.asBinder();
+ r.curApp = app;
+ final ProcessReceiverRecord prr = app.mReceivers;
+ prr.addCurReceiver(r);
+ app.mState.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
+ // Don't bump its LRU position if it's in the background restricted.
+ if (mService.mInternal.getRestrictionLevel(app.info.packageName, app.userId)
+ < RESTRICTION_LEVEL_RESTRICTED_BUCKET) {
+ mService.updateLruProcessLocked(app, false, null);
+ }
+ // Make sure the oom adj score is updated before delivering the broadcast.
+ // Force an update, even if there are other pending requests, overall it still saves time,
+ // because time(updateOomAdj(N apps)) <= N * time(updateOomAdj(1 app)).
+ mService.enqueueOomAdjTargetLocked(app);
+ mService.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_RECEIVER);
+
+ // Tell the application to launch this receiver.
+ maybeReportBroadcastDispatchedEventLocked(r, r.curReceiver.applicationInfo.uid);
+ r.intent.setComponent(r.curComponent);
+
+ boolean started = false;
+ try {
+ if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
+ "Delivering to component " + r.curComponent
+ + ": " + r);
+ mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
+ PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
+ thread.scheduleReceiver(prepareReceiverIntent(r.intent, r.curFilteredExtras),
+ r.curReceiver, null /* compatInfo (unused but need to keep method signature) */,
+ r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
+ app.mState.getReportedProcState());
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "Process cur broadcast " + r + " DELIVERED for app " + app);
+ started = true;
+ } finally {
+ if (!started) {
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "Process cur broadcast " + r + ": NOT STARTED!");
+ r.receiver = null;
+ r.curApp = null;
+ prr.removeCurReceiver(r);
+ }
+ }
+
+ // if something bad happens here, launch the app and try again
+ if (app.isKilled()) {
+ throw new RemoteException("app gets killed during broadcasting");
+ }
+ }
+
+ /**
+ * Called by ActivityManagerService to notify that the uid has process started, if there is any
+ * deferred BOOT_COMPLETED broadcast, the BroadcastDispatcher can dispatch the broadcast now.
+ * @param uid
+ */
+ public void updateUidReadyForBootCompletedBroadcastLocked(int uid) {
+ mDispatcher.updateUidReadyForBootCompletedBroadcastLocked(uid);
+ scheduleBroadcastsLocked();
+ }
+
+ public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
+ boolean didSomething = false;
+ final BroadcastRecord br = mPendingBroadcast;
+ if (br != null && br.curApp.getPid() > 0 && br.curApp.getPid() == app.getPid()) {
+ if (br.curApp != app) {
+ Slog.e(TAG, "App mismatch when sending pending broadcast to "
+ + app.processName + ", intended target is " + br.curApp.processName);
+ return false;
+ }
+ try {
+ mPendingBroadcast = null;
+ br.mIsReceiverAppRunning = false;
+ processCurBroadcastLocked(br, app);
+ didSomething = true;
+ } catch (Exception e) {
+ Slog.w(TAG, "Exception in new application when starting receiver "
+ + br.curComponent.flattenToShortString(), e);
+ logBroadcastReceiverDiscardLocked(br);
+ finishReceiverLocked(br, br.resultCode, br.resultData,
+ br.resultExtras, br.resultAbort, false);
+ scheduleBroadcastsLocked();
+ // We need to reset the state if we failed to start the receiver.
+ br.state = BroadcastRecord.IDLE;
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+ return didSomething;
+ }
+
+ public void skipPendingBroadcastLocked(int pid) {
+ final BroadcastRecord br = mPendingBroadcast;
+ if (br != null && br.curApp.getPid() == pid) {
+ br.state = BroadcastRecord.IDLE;
+ br.nextReceiver = mPendingBroadcastRecvIndex;
+ mPendingBroadcast = null;
+ scheduleBroadcastsLocked();
+ }
+ }
+
+ // Skip the current receiver, if any, that is in flight to the given process
+ public void skipCurrentReceiverLocked(ProcessRecord app) {
+ BroadcastRecord r = null;
+ final BroadcastRecord curActive = mDispatcher.getActiveBroadcastLocked();
+ if (curActive != null && curActive.curApp == app) {
+ // confirmed: the current active broadcast is to the given app
+ r = curActive;
+ }
+
+ // If the current active broadcast isn't this BUT we're waiting for
+ // mPendingBroadcast to spin up the target app, that's what we use.
+ if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "[" + mQueueName + "] skip & discard pending app " + r);
+ r = mPendingBroadcast;
+ }
+
+ if (r != null) {
+ skipReceiverLocked(r);
+ }
+ }
+
+ private void skipReceiverLocked(BroadcastRecord r) {
+ logBroadcastReceiverDiscardLocked(r);
+ finishReceiverLocked(r, r.resultCode, r.resultData,
+ r.resultExtras, r.resultAbort, false);
+ scheduleBroadcastsLocked();
+ }
+
+ public void scheduleBroadcastsLocked() {
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
+ + mQueueName + "]: current="
+ + mBroadcastsScheduled);
+
+ if (mBroadcastsScheduled) {
+ return;
+ }
+ mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
+ mBroadcastsScheduled = true;
+ }
+
+ public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
+ BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
+ if (br != null && br.receiver == receiver) {
+ return br;
+ }
+ return null;
+ }
+
+ // > 0 only, no worry about "eventual" recycling
+ private int nextSplitTokenLocked() {
+ int next = mNextToken + 1;
+ if (next <= 0) {
+ next = 1;
+ }
+ mNextToken = next;
+ return next;
+ }
+
+ private void postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r) {
+ // the receiver had run for less than allowed bg activity start timeout,
+ // so allow the process to still start activities from bg for some more time
+ String msgToken = (app.toShortString() + r.toString()).intern();
+ // first, if there exists a past scheduled request to remove this token, drop
+ // that request - we don't want the token to be swept from under our feet...
+ mHandler.removeCallbacksAndMessages(msgToken);
+ // ...then schedule the removal of the token after the extended timeout
+ mHandler.postAtTime(() -> {
+ synchronized (mService) {
+ app.removeAllowBackgroundActivityStartsToken(r);
+ }
+ }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT));
+ }
+
+ public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
+ String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
+ final int state = r.state;
+ final ActivityInfo receiver = r.curReceiver;
+ final long finishTime = SystemClock.uptimeMillis();
+ final long elapsed = finishTime - r.receiverTime;
+ r.state = BroadcastRecord.IDLE;
+ final int curIndex = r.nextReceiver - 1;
+ if (curIndex >= 0 && curIndex < r.receivers.size() && r.curApp != null) {
+ final Object curReceiver = r.receivers.get(curIndex);
+ FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED, r.curApp.uid,
+ r.callingUid == -1 ? Process.SYSTEM_UID : r.callingUid,
+ ActivityManagerService.getShortAction(r.intent.getAction()),
+ curReceiver instanceof BroadcastFilter
+ ? BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME
+ : BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST,
+ r.mIsReceiverAppRunning
+ ? BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM
+ : BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD,
+ r.dispatchTime - r.enqueueTime,
+ r.receiverTime - r.dispatchTime,
+ finishTime - r.receiverTime);
+ }
+ if (state == BroadcastRecord.IDLE) {
+ Slog.w(TAG_BROADCAST, "finishReceiver [" + mQueueName + "] called but state is IDLE");
+ }
+ if (r.allowBackgroundActivityStarts && r.curApp != null) {
+ if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) {
+ // if the receiver has run for more than allowed bg activity start timeout,
+ // just remove the token for this process now and we're done
+ r.curApp.removeAllowBackgroundActivityStartsToken(r);
+ } else {
+ // It gets more time; post the removal to happen at the appropriate moment
+ postActivityStartTokenRemoval(r.curApp, r);
+ }
+ }
+ // If we're abandoning this broadcast before any receivers were actually spun up,
+ // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply.
+ if (r.nextReceiver > 0) {
+ r.duration[r.nextReceiver - 1] = elapsed;
+ }
+
+ // if this receiver was slow, impose deferral policy on the app. This will kick in
+ // when processNextBroadcastLocked() next finds this uid as a receiver identity.
+ if (!r.timeoutExempt) {
+ // r.curApp can be null if finish has raced with process death - benign
+ // edge case, and we just ignore it because we're already cleaning up
+ // as expected.
+ if (r.curApp != null
+ && mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) {
+ // Core system packages are exempt from deferral policy
+ if (!UserHandle.isCore(r.curApp.uid)) {
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST, "Broadcast receiver " + (r.nextReceiver - 1)
+ + " was slow: " + receiver + " br=" + r);
+ }
+ mDispatcher.startDeferring(r.curApp.uid);
+ } else {
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST, "Core uid " + r.curApp.uid
+ + " receiver was slow but not deferring: "
+ + receiver + " br=" + r);
+ }
+ }
+ }
+ } else {
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction()
+ + " is exempt from deferral policy");
+ }
+ }
+
+ r.receiver = null;
+ r.intent.setComponent(null);
+ if (r.curApp != null && r.curApp.mReceivers.hasCurReceiver(r)) {
+ r.curApp.mReceivers.removeCurReceiver(r);
+ mService.enqueueOomAdjTargetLocked(r.curApp);
+ }
+ if (r.curFilter != null) {
+ r.curFilter.receiverList.curBroadcast = null;
+ }
+ r.curFilter = null;
+ r.curReceiver = null;
+ r.curApp = null;
+ r.curFilteredExtras = null;
+ mPendingBroadcast = null;
+
+ r.resultCode = resultCode;
+ r.resultData = resultData;
+ r.resultExtras = resultExtras;
+ if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
+ r.resultAbort = resultAbort;
+ } else {
+ r.resultAbort = false;
+ }
+
+ // If we want to wait behind services *AND* we're finishing the head/
+ // active broadcast on its queue
+ if (waitForServices && r.curComponent != null && r.queue.isDelayBehindServices()
+ && r.queue.getActiveBroadcastLocked() == r) {
+ ActivityInfo nextReceiver;
+ if (r.nextReceiver < r.receivers.size()) {
+ Object obj = r.receivers.get(r.nextReceiver);
+ nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
+ } else {
+ nextReceiver = null;
+ }
+ // Don't do this if the next receive is in the same process as the current one.
+ if (receiver == null || nextReceiver == null
+ || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
+ || !receiver.processName.equals(nextReceiver.processName)) {
+ // In this case, we are ready to process the next receiver for the current broadcast,
+ // but are on a queue that would like to wait for services to finish before moving
+ // on. If there are background services currently starting, then we will go into a
+ // special state where we hold off on continuing this broadcast until they are done.
+ if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
+ Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
+ r.state = BroadcastRecord.WAITING_SERVICES;
+ return false;
+ }
+ }
+ }
+
+ r.curComponent = null;
+
+ // We will process the next receiver right now if this is finishing
+ // an app receiver (which is always asynchronous) or after we have
+ // come back from calling a receiver.
+ return state == BroadcastRecord.APP_RECEIVE
+ || state == BroadcastRecord.CALL_DONE_RECEIVE;
+ }
+
+ public void backgroundServicesFinishedLocked(int userId) {
+ BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
+ if (br != null) {
+ if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
+ Slog.i(TAG, "Resuming delayed broadcast");
+ br.curComponent = null;
+ br.state = BroadcastRecord.IDLE;
+ processNextBroadcastLocked(false, false);
+ }
+ }
+ }
+
+ public void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
+ Intent intent, int resultCode, String data, Bundle extras,
+ boolean ordered, boolean sticky, int sendingUser,
+ int receiverUid, int callingUid, long dispatchDelay,
+ long receiveDelay) throws RemoteException {
+ // Send the intent to the receiver asynchronously using one-way binder calls.
+ if (app != null) {
+ final IApplicationThread thread = app.getThread();
+ if (thread != null) {
+ // If we have an app thread, do the call through that so it is
+ // correctly ordered with other one-way calls.
+ try {
+ thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
+ data, extras, ordered, sticky, sendingUser,
+ app.mState.getReportedProcState());
+ // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
+ // DeadObjectException when the process isn't actually dead.
+ //} catch (DeadObjectException ex) {
+ // Failed to call into the process. It's dying so just let it die and move on.
+ // throw ex;
+ } catch (RemoteException ex) {
+ // Failed to call into the process. It's either dying or wedged. Kill it gently.
+ synchronized (mService) {
+ Slog.w(TAG, "Can't deliver broadcast to " + app.processName
+ + " (pid " + app.getPid() + "). Crashing it.");
+ app.scheduleCrashLocked("can't deliver broadcast",
+ CannotDeliverBroadcastException.TYPE_ID, /* extras=*/ null);
+ }
+ throw ex;
+ }
+ } else {
+ // Application has died. Receiver doesn't exist.
+ throw new RemoteException("app.thread must not be null");
+ }
+ } else {
+ receiver.performReceive(intent, resultCode, data, extras, ordered,
+ sticky, sendingUser);
+ }
+ if (!ordered) {
+ FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED,
+ receiverUid == -1 ? Process.SYSTEM_UID : receiverUid,
+ callingUid == -1 ? Process.SYSTEM_UID : callingUid,
+ ActivityManagerService.getShortAction(intent.getAction()),
+ BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME,
+ BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM,
+ dispatchDelay, receiveDelay, 0 /* finish_delay */);
+ }
+ }
+
+ private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
+ BroadcastFilter filter, boolean ordered, int index) {
+ boolean skip = mSkipPolicy.shouldSkip(r, filter);
+
+ // Filter packages in the intent extras, skipping delivery if none of the packages is
+ // visible to the receiver.
+ Bundle filteredExtras = null;
+ if (!skip && r.filterExtrasForReceiver != null) {
+ final Bundle extras = r.intent.getExtras();
+ if (extras != null) {
+ filteredExtras = r.filterExtrasForReceiver.apply(filter.receiverList.uid, extras);
+ if (filteredExtras == null) {
+ if (DEBUG_BROADCAST) {
+ Slog.v(TAG, "Skipping delivery to "
+ + filter.receiverList.app
+ + " : receiver is filtered by the package visibility");
+ }
+ skip = true;
+ }
+ }
+ }
+
+ if (skip) {
+ r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
+ return;
+ }
+
+ r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
+
+ // If this is not being sent as an ordered broadcast, then we
+ // don't want to touch the fields that keep track of the current
+ // state of ordered broadcasts.
+ if (ordered) {
+ r.receiver = filter.receiverList.receiver.asBinder();
+ r.curFilter = filter;
+ filter.receiverList.curBroadcast = r;
+ r.state = BroadcastRecord.CALL_IN_RECEIVE;
+ if (filter.receiverList.app != null) {
+ // Bump hosting application to no longer be in background
+ // scheduling class. Note that we can't do that if there
+ // isn't an app... but we can only be in that case for
+ // things that directly call the IActivityManager API, which
+ // are already core system stuff so don't matter for this.
+ r.curApp = filter.receiverList.app;
+ filter.receiverList.app.mReceivers.addCurReceiver(r);
+ mService.enqueueOomAdjTargetLocked(r.curApp);
+ mService.updateOomAdjPendingTargetsLocked(
+ OOM_ADJ_REASON_START_RECEIVER);
+ }
+ } else if (filter.receiverList.app != null) {
+ mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(filter.receiverList.app,
+ OOM_ADJ_REASON_START_RECEIVER);
+ }
+
+ try {
+ if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
+ "Delivering to " + filter + " : " + r);
+ if (filter.receiverList.app != null && filter.receiverList.app.isInFullBackup()) {
+ // Skip delivery if full backup in progress
+ // If it's an ordered broadcast, we need to continue to the next receiver.
+ if (ordered) {
+ skipReceiverLocked(r);
+ }
+ } else {
+ r.receiverTime = SystemClock.uptimeMillis();
+ maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
+ maybeScheduleTempAllowlistLocked(filter.owningUid, r, r.options);
+ maybeReportBroadcastDispatchedEventLocked(r, filter.owningUid);
+ performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
+ prepareReceiverIntent(r.intent, filteredExtras), r.resultCode, r.resultData,
+ r.resultExtras, r.ordered, r.initialSticky, r.userId,
+ filter.receiverList.uid, r.callingUid,
+ r.dispatchTime - r.enqueueTime,
+ r.receiverTime - r.dispatchTime);
+ // parallel broadcasts are fire-and-forget, not bookended by a call to
+ // finishReceiverLocked(), so we manage their activity-start token here
+ if (filter.receiverList.app != null
+ && r.allowBackgroundActivityStarts && !r.ordered) {
+ postActivityStartTokenRemoval(filter.receiverList.app, r);
+ }
+ }
+ if (ordered) {
+ r.state = BroadcastRecord.CALL_DONE_RECEIVE;
+ }
+ } catch (RemoteException e) {
+ Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
+ // Clean up ProcessRecord state related to this broadcast attempt
+ if (filter.receiverList.app != null) {
+ filter.receiverList.app.removeAllowBackgroundActivityStartsToken(r);
+ if (ordered) {
+ filter.receiverList.app.mReceivers.removeCurReceiver(r);
+ // Something wrong, its oom adj could be downgraded, but not in a hurry.
+ mService.enqueueOomAdjTargetLocked(r.curApp);
+ }
+ }
+ // And BroadcastRecord state related to ordered delivery, if appropriate
+ if (ordered) {
+ r.receiver = null;
+ r.curFilter = null;
+ filter.receiverList.curBroadcast = null;
+ }
+ }
+ }
+
+ void maybeScheduleTempAllowlistLocked(int uid, BroadcastRecord r,
+ @Nullable BroadcastOptions brOptions) {
+ if (brOptions == null || brOptions.getTemporaryAppAllowlistDuration() <= 0) {
+ return;
+ }
+ long duration = brOptions.getTemporaryAppAllowlistDuration();
+ final @TempAllowListType int type = brOptions.getTemporaryAppAllowlistType();
+ final @ReasonCode int reasonCode = brOptions.getTemporaryAppAllowlistReasonCode();
+ final String reason = brOptions.getTemporaryAppAllowlistReason();
+
+ if (duration > Integer.MAX_VALUE) {
+ duration = Integer.MAX_VALUE;
+ }
+ // XXX ideally we should pause the broadcast until everything behind this is done,
+ // or else we will likely start dispatching the broadcast before we have opened
+ // access to the app (there is a lot of asynchronicity behind this). It is probably
+ // not that big a deal, however, because the main purpose here is to allow apps
+ // to hold wake locks, and they will be able to acquire their wake lock immediately
+ // it just won't be enabled until we get through this work.
+ StringBuilder b = new StringBuilder();
+ b.append("broadcast:");
+ UserHandle.formatUid(b, r.callingUid);
+ b.append(":");
+ if (r.intent.getAction() != null) {
+ b.append(r.intent.getAction());
+ } else if (r.intent.getComponent() != null) {
+ r.intent.getComponent().appendShortString(b);
+ } else if (r.intent.getData() != null) {
+ b.append(r.intent.getData());
+ }
+ b.append(",reason:");
+ b.append(reason);
+ if (DEBUG_BROADCAST) {
+ Slog.v(TAG, "Broadcast temp allowlist uid=" + uid + " duration=" + duration
+ + " type=" + type + " : " + b.toString());
+ }
+ mService.tempAllowlistUidLocked(uid, duration, reasonCode, b.toString(), type,
+ r.callingUid);
+ }
+
+ private void processNextBroadcast(boolean fromMsg) {
+ synchronized (mService) {
+ processNextBroadcastLocked(fromMsg, false);
+ }
+ }
+
+ private static Intent prepareReceiverIntent(@NonNull Intent originalIntent,
+ @Nullable Bundle filteredExtras) {
+ final Intent intent = new Intent(originalIntent);
+ if (filteredExtras != null) {
+ intent.replaceExtras(filteredExtras);
+ }
+ return intent;
+ }
+
+ public void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
+ BroadcastRecord r;
+
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
+ + mQueueName + "]: "
+ + mParallelBroadcasts.size() + " parallel broadcasts; "
+ + mDispatcher.describeStateLocked());
+
+ mService.updateCpuStats();
+
+ if (fromMsg) {
+ mBroadcastsScheduled = false;
+ }
+
+ // First, deliver any non-serialized broadcasts right away.
+ while (mParallelBroadcasts.size() > 0) {
+ r = mParallelBroadcasts.remove(0);
+ r.dispatchTime = SystemClock.uptimeMillis();
+ r.dispatchRealTime = SystemClock.elapsedRealtime();
+ r.dispatchClockTime = System.currentTimeMillis();
+ r.mIsReceiverAppRunning = true;
+
+ if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
+ Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
+ createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
+ System.identityHashCode(r));
+ Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
+ createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
+ System.identityHashCode(r));
+ }
+
+ final int N = r.receivers.size();
+ if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
+ + mQueueName + "] " + r);
+ for (int i=0; i<N; i++) {
+ Object target = r.receivers.get(i);
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "Delivering non-ordered on [" + mQueueName + "] to registered "
+ + target + ": " + r);
+ deliverToRegisteredReceiverLocked(r,
+ (BroadcastFilter) target, false, i);
+ }
+ addBroadcastToHistoryLocked(r);
+ if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
+ + mQueueName + "] " + r);
+ }
+
+ // Now take care of the next serialized one...
+
+ // If we are waiting for a process to come up to handle the next
+ // broadcast, then do nothing at this point. Just in case, we
+ // check that the process we're waiting for still exists.
+ if (mPendingBroadcast != null) {
+ if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
+ "processNextBroadcast [" + mQueueName + "]: waiting for "
+ + mPendingBroadcast.curApp);
+
+ boolean isDead;
+ if (mPendingBroadcast.curApp.getPid() > 0) {
+ synchronized (mService.mPidsSelfLocked) {
+ ProcessRecord proc = mService.mPidsSelfLocked.get(
+ mPendingBroadcast.curApp.getPid());
+ isDead = proc == null || proc.mErrorState.isCrashing();
+ }
+ } else {
+ final ProcessRecord proc = mService.mProcessList.getProcessNamesLOSP().get(
+ mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid);
+ isDead = proc == null || !proc.isPendingStart();
+ }
+ if (!isDead) {
+ // It's still alive, so keep waiting
+ return;
+ } else {
+ Slog.w(TAG, "pending app ["
+ + mQueueName + "]" + mPendingBroadcast.curApp
+ + " died before responding to broadcast");
+ mPendingBroadcast.state = BroadcastRecord.IDLE;
+ mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
+ mPendingBroadcast = null;
+ }
+ }
+
+ boolean looped = false;
+
+ do {
+ final long now = SystemClock.uptimeMillis();
+ r = mDispatcher.getNextBroadcastLocked(now);
+
+ if (r == null) {
+ // No more broadcasts are deliverable right now, so all done!
+ mDispatcher.scheduleDeferralCheckLocked(false);
+ synchronized (mService.mAppProfiler.mProfilerLock) {
+ mService.mAppProfiler.scheduleAppGcsLPf();
+ }
+ if (looped && !skipOomAdj) {
+ // If we had finished the last ordered broadcast, then
+ // make sure all processes have correct oom and sched
+ // adjustments.
+ mService.updateOomAdjPendingTargetsLocked(
+ OOM_ADJ_REASON_START_RECEIVER);
+ }
+
+ // when we have no more ordered broadcast on this queue, stop logging
+ if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) {
+ mLogLatencyMetrics = false;
+ }
+
+ return;
+ }
+
+ boolean forceReceive = false;
+
+ // Ensure that even if something goes awry with the timeout
+ // detection, we catch "hung" broadcasts here, discard them,
+ // and continue to make progress.
+ //
+ // This is only done if the system is ready so that early-stage receivers
+ // don't get executed with timeouts; and of course other timeout-
+ // exempt broadcasts are ignored.
+ int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
+ if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
+ if ((numReceivers > 0) &&
+ (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) {
+ Slog.w(TAG, "Hung broadcast ["
+ + mQueueName + "] discarded after timeout failure:"
+ + " now=" + now
+ + " dispatchTime=" + r.dispatchTime
+ + " startTime=" + r.receiverTime
+ + " intent=" + r.intent
+ + " numReceivers=" + numReceivers
+ + " nextReceiver=" + r.nextReceiver
+ + " state=" + r.state);
+ broadcastTimeoutLocked(false); // forcibly finish this broadcast
+ forceReceive = true;
+ r.state = BroadcastRecord.IDLE;
+ }
+ }
+
+ if (r.state != BroadcastRecord.IDLE) {
+ if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
+ "processNextBroadcast("
+ + mQueueName + ") called when not idle (state="
+ + r.state + ")");
+ return;
+ }
+
+ // Is the current broadcast is done for any reason?
+ if (r.receivers == null || r.nextReceiver >= numReceivers
+ || r.resultAbort || forceReceive) {
+ // Send the final result if requested
+ if (r.resultTo != null) {
+ boolean sendResult = true;
+
+ // if this was part of a split/deferral complex, update the refcount and only
+ // send the completion when we clear all of them
+ if (r.splitToken != 0) {
+ int newCount = mSplitRefcounts.get(r.splitToken) - 1;
+ if (newCount == 0) {
+ // done! clear out this record's bookkeeping and deliver
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST,
+ "Sending broadcast completion for split token "
+ + r.splitToken + " : " + r.intent.getAction());
+ }
+ mSplitRefcounts.delete(r.splitToken);
+ } else {
+ // still have some split broadcast records in flight; update refcount
+ // and hold off on the callback
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST,
+ "Result refcount now " + newCount + " for split token "
+ + r.splitToken + " : " + r.intent.getAction()
+ + " - not sending completion yet");
+ }
+ sendResult = false;
+ mSplitRefcounts.put(r.splitToken, newCount);
+ }
+ }
+ if (sendResult) {
+ if (r.callerApp != null) {
+ mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(
+ r.callerApp, OOM_ADJ_REASON_FINISH_RECEIVER);
+ }
+ try {
+ if (DEBUG_BROADCAST) {
+ Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] "
+ + r.intent.getAction() + " app=" + r.callerApp);
+ }
+ if (r.dispatchTime == 0) {
+ // The dispatch time here could be 0, in case it's a parallel
+ // broadcast but it has a result receiver. Set it to now.
+ r.dispatchTime = now;
+ }
+ r.mIsReceiverAppRunning = true;
+ performReceiveLocked(r.callerApp, r.resultTo,
+ new Intent(r.intent), r.resultCode,
+ r.resultData, r.resultExtras, false, false, r.userId,
+ r.callingUid, r.callingUid,
+ r.dispatchTime - r.enqueueTime,
+ now - r.dispatchTime);
+ logBootCompletedBroadcastCompletionLatencyIfPossible(r);
+ // Set this to null so that the reference
+ // (local and remote) isn't kept in the mBroadcastHistory.
+ r.resultTo = null;
+ } catch (RemoteException e) {
+ r.resultTo = null;
+ Slog.w(TAG, "Failure ["
+ + mQueueName + "] sending broadcast result of "
+ + r.intent, e);
+ }
+ }
+ }
+
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
+ cancelBroadcastTimeoutLocked();
+
+ if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
+ "Finished with ordered broadcast " + r);
+
+ // ... and on to the next...
+ addBroadcastToHistoryLocked(r);
+ if (r.intent.getComponent() == null && r.intent.getPackage() == null
+ && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
+ // This was an implicit broadcast... let's record it for posterity.
+ mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
+ r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
+ }
+ mDispatcher.retireBroadcastLocked(r);
+ r = null;
+ looped = true;
+ continue;
+ }
+
+ // Check whether the next receiver is under deferral policy, and handle that
+ // accordingly. If the current broadcast was already part of deferred-delivery
+ // tracking, we know that it must now be deliverable as-is without re-deferral.
+ if (!r.deferred) {
+ final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver));
+ if (mDispatcher.isDeferringLocked(receiverUid)) {
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid
+ + " at " + r.nextReceiver + " is under deferral");
+ }
+ // If this is the only (remaining) receiver in the broadcast, "splitting"
+ // doesn't make sense -- just defer it as-is and retire it as the
+ // currently active outgoing broadcast.
+ BroadcastRecord defer;
+ if (r.nextReceiver + 1 == numReceivers) {
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST, "Sole receiver of " + r
+ + " is under deferral; setting aside and proceeding");
+ }
+ defer = r;
+ mDispatcher.retireBroadcastLocked(r);
+ } else {
+ // Nontrivial case; split out 'uid's receivers to a new broadcast record
+ // and defer that, then loop and pick up continuing delivery of the current
+ // record (now absent those receivers).
+
+ // The split operation is guaranteed to match at least at 'nextReceiver'
+ defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver);
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST, "Post split:");
+ Slog.i(TAG_BROADCAST, "Original broadcast receivers:");
+ for (int i = 0; i < r.receivers.size(); i++) {
+ Slog.i(TAG_BROADCAST, " " + r.receivers.get(i));
+ }
+ Slog.i(TAG_BROADCAST, "Split receivers:");
+ for (int i = 0; i < defer.receivers.size(); i++) {
+ Slog.i(TAG_BROADCAST, " " + defer.receivers.get(i));
+ }
+ }
+ // Track completion refcount as well if relevant
+ if (r.resultTo != null) {
+ int token = r.splitToken;
+ if (token == 0) {
+ // first split of this record; refcount for 'r' and 'deferred'
+ r.splitToken = defer.splitToken = nextSplitTokenLocked();
+ mSplitRefcounts.put(r.splitToken, 2);
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST,
+ "Broadcast needs split refcount; using new token "
+ + r.splitToken);
+ }
+ } else {
+ // new split from an already-refcounted situation; increment count
+ final int curCount = mSplitRefcounts.get(token);
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ if (curCount == 0) {
+ Slog.wtf(TAG_BROADCAST,
+ "Split refcount is zero with token for " + r);
+ }
+ }
+ mSplitRefcounts.put(token, curCount + 1);
+ if (DEBUG_BROADCAST_DEFERRAL) {
+ Slog.i(TAG_BROADCAST, "New split count for token " + token
+ + " is " + (curCount + 1));
+ }
+ }
+ }
+ }
+ mDispatcher.addDeferredBroadcast(receiverUid, defer);
+ r = null;
+ looped = true;
+ continue;
+ }
+ }
+ } while (r == null);
+
+ // Get the next receiver...
+ int recIdx = r.nextReceiver++;
+
+ // Keep track of when this receiver started, and make sure there
+ // is a timeout message pending to kill it if need be.
+ r.receiverTime = SystemClock.uptimeMillis();
+ if (recIdx == 0) {
+ r.dispatchTime = r.receiverTime;
+ r.dispatchRealTime = SystemClock.elapsedRealtime();
+ r.dispatchClockTime = System.currentTimeMillis();
+
+ if (mLogLatencyMetrics) {
+ FrameworkStatsLog.write(
+ FrameworkStatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED,
+ r.dispatchClockTime - r.enqueueClockTime);
+ }
+
+ if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
+ Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
+ createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
+ System.identityHashCode(r));
+ Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
+ createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
+ System.identityHashCode(r));
+ }
+ if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
+ + mQueueName + "] " + r);
+ }
+ if (! mPendingBroadcastTimeoutMessage) {
+ long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "Submitting BROADCAST_TIMEOUT_MSG ["
+ + mQueueName + "] for " + r + " at " + timeoutTime);
+ setBroadcastTimeoutLocked(timeoutTime);
+ }
+
+ final BroadcastOptions brOptions = r.options;
+ final Object nextReceiver = r.receivers.get(recIdx);
+
+ if (nextReceiver instanceof BroadcastFilter) {
+ // Simple case: this is a registered receiver who gets
+ // a direct call.
+ BroadcastFilter filter = (BroadcastFilter)nextReceiver;
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "Delivering ordered ["
+ + mQueueName + "] to registered "
+ + filter + ": " + r);
+ r.mIsReceiverAppRunning = true;
+ deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
+ if (r.receiver == null || !r.ordered) {
+ // The receiver has already finished, so schedule to
+ // process the next one.
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
+ + mQueueName + "]: ordered="
+ + r.ordered + " receiver=" + r.receiver);
+ r.state = BroadcastRecord.IDLE;
+ scheduleBroadcastsLocked();
+ } else {
+ if (filter.receiverList != null) {
+ maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
+ // r is guaranteed ordered at this point, so we know finishReceiverLocked()
+ // will get a callback and handle the activity start token lifecycle.
+ }
+ }
+ return;
+ }
+
+ // Hard case: need to instantiate the receiver, possibly
+ // starting its application process to host it.
+
+ final ResolveInfo info =
+ (ResolveInfo)nextReceiver;
+ final ComponentName component = new ComponentName(
+ info.activityInfo.applicationInfo.packageName,
+ info.activityInfo.name);
+ final int receiverUid = info.activityInfo.applicationInfo.uid;
+
+ final String targetProcess = info.activityInfo.processName;
+ final ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
+ info.activityInfo.applicationInfo.uid);
+
+ boolean skip = mSkipPolicy.shouldSkip(r, info);
+
+ // Filter packages in the intent extras, skipping delivery if none of the packages is
+ // visible to the receiver.
+ Bundle filteredExtras = null;
+ if (!skip && r.filterExtrasForReceiver != null) {
+ final Bundle extras = r.intent.getExtras();
+ if (extras != null) {
+ filteredExtras = r.filterExtrasForReceiver.apply(receiverUid, extras);
+ if (filteredExtras == null) {
+ if (DEBUG_BROADCAST) {
+ Slog.v(TAG, "Skipping delivery to "
+ + info.activityInfo.packageName + " / " + receiverUid
+ + " : receiver is filtered by the package visibility");
+ }
+ skip = true;
+ }
+ }
+ }
+
+ if (skip) {
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "Skipping delivery of ordered [" + mQueueName + "] "
+ + r + " for reason described above");
+ r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
+ r.receiver = null;
+ r.curFilter = null;
+ r.state = BroadcastRecord.IDLE;
+ r.manifestSkipCount++;
+ scheduleBroadcastsLocked();
+ return;
+ }
+ r.manifestCount++;
+
+ r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
+ r.state = BroadcastRecord.APP_RECEIVE;
+ r.curComponent = component;
+ r.curReceiver = info.activityInfo;
+ r.curFilteredExtras = filteredExtras;
+ if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
+ Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
+ + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
+ + receiverUid);
+ }
+ final boolean isActivityCapable =
+ (brOptions != null && brOptions.getTemporaryAppAllowlistDuration() > 0);
+ maybeScheduleTempAllowlistLocked(receiverUid, r, brOptions);
+
+ // Report that a component is used for explicit broadcasts.
+ if (r.intent.getComponent() != null && r.curComponent != null
+ && !TextUtils.equals(r.curComponent.getPackageName(), r.callerPackage)) {
+ mService.mUsageStatsService.reportEvent(
+ r.curComponent.getPackageName(), r.userId, Event.APP_COMPONENT_USED);
+ }
+
+ // Broadcast is being executed, its package can't be stopped.
+ try {
+ AppGlobals.getPackageManager().setPackageStoppedState(
+ r.curComponent.getPackageName(), false, r.userId);
+ } catch (RemoteException e) {
+ } catch (IllegalArgumentException e) {
+ Slog.w(TAG, "Failed trying to unstop package "
+ + r.curComponent.getPackageName() + ": " + e);
+ }
+
+ // Is this receiver's application already running?
+ if (app != null && app.getThread() != null && !app.isKilled()) {
+ try {
+ app.addPackage(info.activityInfo.packageName,
+ info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats);
+ maybeAddAllowBackgroundActivityStartsToken(app, r);
+ r.mIsReceiverAppRunning = true;
+ processCurBroadcastLocked(r, app);
+ return;
+ } catch (RemoteException e) {
+ Slog.w(TAG, "Exception when sending broadcast to "
+ + r.curComponent, e);
+ } catch (RuntimeException e) {
+ Slog.wtf(TAG, "Failed sending broadcast to "
+ + r.curComponent + " with " + r.intent, e);
+ // If some unexpected exception happened, just skip
+ // this broadcast. At this point we are not in the call
+ // from a client, so throwing an exception out from here
+ // will crash the entire system instead of just whoever
+ // sent the broadcast.
+ logBroadcastReceiverDiscardLocked(r);
+ finishReceiverLocked(r, r.resultCode, r.resultData,
+ r.resultExtras, r.resultAbort, false);
+ scheduleBroadcastsLocked();
+ // We need to reset the state if we failed to start the receiver.
+ r.state = BroadcastRecord.IDLE;
+ return;
+ }
+
+ // If a dead object exception was thrown -- fall through to
+ // restart the application.
+ }
+
+ // Not running -- get it started, to be executed when the app comes up.
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "Need to start app ["
+ + mQueueName + "] " + targetProcess + " for broadcast " + r);
+ r.curApp = mService.startProcessLocked(targetProcess,
+ info.activityInfo.applicationInfo, true,
+ r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
+ new HostingRecord(HostingRecord.HOSTING_TYPE_BROADCAST, r.curComponent,
+ r.intent.getAction(), getHostingRecordTriggerType(r)),
+ isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY,
+ (r.intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false);
+ if (r.curApp == null) {
+ // Ah, this recipient is unavailable. Finish it if necessary,
+ // and mark the broadcast record as ready for the next.
+ Slog.w(TAG, "Unable to launch app "
+ + info.activityInfo.applicationInfo.packageName + "/"
+ + receiverUid + " for broadcast "
+ + r.intent + ": process is bad");
+ logBroadcastReceiverDiscardLocked(r);
+ finishReceiverLocked(r, r.resultCode, r.resultData,
+ r.resultExtras, r.resultAbort, false);
+ scheduleBroadcastsLocked();
+ r.state = BroadcastRecord.IDLE;
+ return;
+ }
+
+ maybeAddAllowBackgroundActivityStartsToken(r.curApp, r);
+ mPendingBroadcast = r;
+ mPendingBroadcastRecvIndex = recIdx;
+ }
+
+ private String getHostingRecordTriggerType(BroadcastRecord r) {
+ if (r.alarm) {
+ return HostingRecord.TRIGGER_TYPE_ALARM;
+ } else if (r.pushMessage) {
+ return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE;
+ } else if (r.pushMessageOverQuota) {
+ return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE_OVER_QUOTA;
+ }
+ return HostingRecord.TRIGGER_TYPE_UNKNOWN;
+ }
+
+ @Nullable
+ private String getTargetPackage(BroadcastRecord r) {
+ if (r.intent == null) {
+ return null;
+ }
+ if (r.intent.getPackage() != null) {
+ return r.intent.getPackage();
+ } else if (r.intent.getComponent() != null) {
+ return r.intent.getComponent().getPackageName();
+ }
+ return null;
+ }
+
+ private void logBootCompletedBroadcastCompletionLatencyIfPossible(BroadcastRecord r) {
+ // Only log after last receiver.
+ // In case of split BOOT_COMPLETED broadcast, make sure only call this method on the
+ // last BroadcastRecord of the split broadcast which has non-null resultTo.
+ final int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
+ if (r.nextReceiver < numReceivers) {
+ return;
+ }
+ final String action = r.intent.getAction();
+ int event = 0;
+ if (Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action)) {
+ event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED;
+ } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
+ event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED;
+ }
+ if (event != 0) {
+ final int dispatchLatency = (int)(r.dispatchTime - r.enqueueTime);
+ final int completeLatency = (int)
+ (SystemClock.uptimeMillis() - r.enqueueTime);
+ final int dispatchRealLatency = (int)(r.dispatchRealTime - r.enqueueRealTime);
+ final int completeRealLatency = (int)
+ (SystemClock.elapsedRealtime() - r.enqueueRealTime);
+ int userType = FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__TYPE_UNKNOWN;
+ // This method is called very infrequently, no performance issue we call
+ // LocalServices.getService() here.
+ final UserManagerInternal umInternal = LocalServices.getService(
+ UserManagerInternal.class);
+ final UserInfo userInfo = umInternal.getUserInfo(r.userId);
+ if (userInfo != null) {
+ userType = UserManager.getUserTypeForStatsd(userInfo.userType);
+ }
+ Slog.i(TAG_BROADCAST,
+ "BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED action:"
+ + action
+ + " dispatchLatency:" + dispatchLatency
+ + " completeLatency:" + completeLatency
+ + " dispatchRealLatency:" + dispatchRealLatency
+ + " completeRealLatency:" + completeRealLatency
+ + " receiversSize:" + numReceivers
+ + " userId:" + r.userId
+ + " userType:" + (userInfo != null? userInfo.userType : null));
+ FrameworkStatsLog.write(
+ BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED,
+ event,
+ dispatchLatency,
+ completeLatency,
+ dispatchRealLatency,
+ completeRealLatency,
+ r.userId,
+ userType);
+ }
+ }
+
+ private void maybeReportBroadcastDispatchedEventLocked(BroadcastRecord r, int targetUid) {
+ if (r.options == null || r.options.getIdForResponseEvent() <= 0) {
+ return;
+ }
+ final String targetPackage = getTargetPackage(r);
+ // Ignore non-explicit broadcasts
+ if (targetPackage == null) {
+ return;
+ }
+ getUsageStatsManagerInternal().reportBroadcastDispatched(
+ r.callingUid, targetPackage, UserHandle.of(r.userId),
+ r.options.getIdForResponseEvent(), SystemClock.elapsedRealtime(),
+ mService.getUidStateLocked(targetUid));
+ }
+
+ @NonNull
+ private UsageStatsManagerInternal getUsageStatsManagerInternal() {
+ final UsageStatsManagerInternal usageStatsManagerInternal =
+ LocalServices.getService(UsageStatsManagerInternal.class);
+ return usageStatsManagerInternal;
+ }
+
+ private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) {
+ if (r == null || proc == null || !r.allowBackgroundActivityStarts) {
+ return;
+ }
+ String msgToken = (proc.toShortString() + r.toString()).intern();
+ // first, if there exists a past scheduled request to remove this token, drop
+ // that request - we don't want the token to be swept from under our feet...
+ mHandler.removeCallbacksAndMessages(msgToken);
+ // ...then add the token
+ proc.addOrUpdateAllowBackgroundActivityStartsToken(r, r.mBackgroundActivityStartsToken);
+ }
+
+ final void setBroadcastTimeoutLocked(long timeoutTime) {
+ if (! mPendingBroadcastTimeoutMessage) {
+ Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
+ mHandler.sendMessageAtTime(msg, timeoutTime);
+ mPendingBroadcastTimeoutMessage = true;
+ }
+ }
+
+ final void cancelBroadcastTimeoutLocked() {
+ if (mPendingBroadcastTimeoutMessage) {
+ mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
+ mPendingBroadcastTimeoutMessage = false;
+ }
+ }
+
+ final void broadcastTimeoutLocked(boolean fromMsg) {
+ if (fromMsg) {
+ mPendingBroadcastTimeoutMessage = false;
+ }
+
+ if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) {
+ return;
+ }
+
+ long now = SystemClock.uptimeMillis();
+ BroadcastRecord r = mDispatcher.getActiveBroadcastLocked();
+ if (fromMsg) {
+ if (!mService.mProcessesReady) {
+ // Only process broadcast timeouts if the system is ready; some early
+ // broadcasts do heavy work setting up system facilities
+ return;
+ }
+
+ // If the broadcast is generally exempt from timeout tracking, we're done
+ if (r.timeoutExempt) {
+ if (DEBUG_BROADCAST) {
+ Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: "
+ + r.intent.getAction());
+ }
+ return;
+ }
+
+ long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
+ if (timeoutTime > now) {
+ // We can observe premature timeouts because we do not cancel and reset the
+ // broadcast timeout message after each receiver finishes. Instead, we set up
+ // an initial timeout then kick it down the road a little further as needed
+ // when it expires.
+ if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
+ "Premature timeout ["
+ + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
+ + timeoutTime);
+ setBroadcastTimeoutLocked(timeoutTime);
+ return;
+ }
+ }
+
+ if (r.state == BroadcastRecord.WAITING_SERVICES) {
+ // In this case the broadcast had already finished, but we had decided to wait
+ // for started services to finish as well before going on. So if we have actually
+ // waited long enough time timeout the broadcast, let's give up on the whole thing
+ // and just move on to the next.
+ Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null
+ ? r.curComponent.flattenToShortString() : "(null)"));
+ r.curComponent = null;
+ r.state = BroadcastRecord.IDLE;
+ processNextBroadcastLocked(false, false);
+ return;
+ }
+
+ // If the receiver app is being debugged we quietly ignore unresponsiveness, just
+ // tidying up and moving on to the next broadcast without crashing or ANRing this
+ // app just because it's stopped at a breakpoint.
+ final boolean debugging = (r.curApp != null && r.curApp.isDebugging());
+
+ long timeoutDurationMs = now - r.receiverTime;
+ Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
+ + ", started " + timeoutDurationMs + "ms ago");
+ r.receiverTime = now;
+ if (!debugging) {
+ r.anrCount++;
+ }
+
+ ProcessRecord app = null;
+ TimeoutRecord timeoutRecord = null;
+
+ Object curReceiver;
+ if (r.nextReceiver > 0) {
+ curReceiver = r.receivers.get(r.nextReceiver-1);
+ r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
+ } else {
+ curReceiver = r.curReceiver;
+ }
+ Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
+ logBroadcastReceiverDiscardLocked(r);
+ if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
+ BroadcastFilter bf = (BroadcastFilter)curReceiver;
+ if (bf.receiverList.pid != 0
+ && bf.receiverList.pid != ActivityManagerService.MY_PID) {
+ synchronized (mService.mPidsSelfLocked) {
+ app = mService.mPidsSelfLocked.get(
+ bf.receiverList.pid);
+ }
+ }
+ } else {
+ app = r.curApp;
+ }
+
+ if (app != null) {
+ String anrMessage =
+ "Broadcast of " + r.intent.toString() + ", waited " + timeoutDurationMs
+ + "ms";
+ timeoutRecord = TimeoutRecord.forBroadcastReceiver(anrMessage);
+ }
+
+ if (mPendingBroadcast == r) {
+ mPendingBroadcast = null;
+ }
+
+ // Move on to the next receiver.
+ finishReceiverLocked(r, r.resultCode, r.resultData,
+ r.resultExtras, r.resultAbort, false);
+ scheduleBroadcastsLocked();
+
+ if (!debugging && timeoutRecord != null) {
+ mService.mAnrHelper.appNotResponding(app, timeoutRecord);
+ }
+ }
+
+ private final int ringAdvance(int x, final int increment, final int ringSize) {
+ x += increment;
+ if (x < 0) return (ringSize - 1);
+ else if (x >= ringSize) return 0;
+ else return x;
+ }
+
+ private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
+ if (original.callingUid < 0) {
+ // This was from a registerReceiver() call; ignore it.
+ return;
+ }
+ original.finishTime = SystemClock.uptimeMillis();
+
+ if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
+ Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
+ createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
+ System.identityHashCode(original));
+ }
+
+ final ApplicationInfo info = original.callerApp != null ? original.callerApp.info : null;
+ final String callerPackage = info != null ? info.packageName : original.callerPackage;
+ if (callerPackage != null) {
+ mService.mHandler.obtainMessage(ActivityManagerService.DISPATCH_SENDING_BROADCAST_EVENT,
+ original.callingUid, 0, callerPackage).sendToTarget();
+ }
+
+ // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords,
+ // So don't change the incoming record directly.
+ final BroadcastRecord historyRecord = original.maybeStripForHistory();
+
+ mBroadcastHistory[mHistoryNext] = historyRecord;
+ mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
+
+ mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent;
+ mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime;
+ mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime;
+ mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
+ mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
+ }
+
+ public boolean cleanupDisabledPackageReceiversLocked(
+ String packageName, Set<String> filterByClasses, int userId, boolean doit) {
+ boolean didSomething = false;
+ for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
+ didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
+ packageName, filterByClasses, userId, doit);
+ if (!doit && didSomething) {
+ return true;
+ }
+ }
+
+ didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName,
+ filterByClasses, userId, doit);
+
+ return didSomething;
+ }
+
+ final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
+ final int logIndex = r.nextReceiver - 1;
+ if (logIndex >= 0 && logIndex < r.receivers.size()) {
+ Object curReceiver = r.receivers.get(logIndex);
+ if (curReceiver instanceof BroadcastFilter) {
+ BroadcastFilter bf = (BroadcastFilter) curReceiver;
+ EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
+ bf.owningUserId, System.identityHashCode(r),
+ r.intent.getAction(), logIndex, System.identityHashCode(bf));
+ } else {
+ ResolveInfo ri = (ResolveInfo) curReceiver;
+ EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
+ UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
+ System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
+ }
+ } else {
+ if (logIndex < 0) Slog.w(TAG,
+ "Discarding broadcast before first receiver is invoked: " + r);
+ EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
+ -1, System.identityHashCode(r),
+ r.intent.getAction(),
+ r.nextReceiver,
+ "NONE");
+ }
+ }
+
+ private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
+ return formatSimple("Broadcast %s from %s (%s) %s",
+ state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
+ record.callerPackage == null ? "" : record.callerPackage,
+ record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
+ record.intent == null ? "" : record.intent.getAction());
+ }
+
+ public boolean isIdle() {
+ return mParallelBroadcasts.isEmpty() && mDispatcher.isIdle()
+ && (mPendingBroadcast == null);
+ }
+
+ public void flush() {
+ cancelDeferrals();
+ }
+
+ // Used by wait-for-broadcast-idle : fast-forward all current deferrals to
+ // be immediately deliverable.
+ public void cancelDeferrals() {
+ synchronized (mService) {
+ mDispatcher.cancelDeferralsLocked();
+ scheduleBroadcastsLocked();
+ }
+ }
+
+ public String describeState() {
+ synchronized (mService) {
+ return mParallelBroadcasts.size() + " parallel; "
+ + mDispatcher.describeStateLocked();
+ }
+ }
+
+ public void dumpDebug(ProtoOutputStream proto, long fieldId) {
+ long token = proto.start(fieldId);
+ proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
+ int N;
+ N = mParallelBroadcasts.size();
+ for (int i = N - 1; i >= 0; i--) {
+ mParallelBroadcasts.get(i).dumpDebug(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
+ }
+ mDispatcher.dumpDebug(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
+ if (mPendingBroadcast != null) {
+ mPendingBroadcast.dumpDebug(proto, BroadcastQueueProto.PENDING_BROADCAST);
+ }
+
+ int lastIndex = mHistoryNext;
+ int ringIndex = lastIndex;
+ do {
+ // increasing index = more recent entry, and we want to print the most
+ // recent first and work backwards, so we roll through the ring backwards.
+ ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
+ BroadcastRecord r = mBroadcastHistory[ringIndex];
+ if (r != null) {
+ r.dumpDebug(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS);
+ }
+ } while (ringIndex != lastIndex);
+
+ lastIndex = ringIndex = mSummaryHistoryNext;
+ do {
+ ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
+ Intent intent = mBroadcastSummaryHistory[ringIndex];
+ if (intent == null) {
+ continue;
+ }
+ long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY);
+ intent.dumpDebug(proto, BroadcastQueueProto.BroadcastSummary.INTENT,
+ false, true, true, false);
+ proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS,
+ mSummaryHistoryEnqueueTime[ringIndex]);
+ proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS,
+ mSummaryHistoryDispatchTime[ringIndex]);
+ proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS,
+ mSummaryHistoryFinishTime[ringIndex]);
+ proto.end(summaryToken);
+ } while (ringIndex != lastIndex);
+ proto.end(token);
+ }
+
+ public boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
+ int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
+ if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty()
+ || mPendingBroadcast != null) {
+ boolean printed = false;
+ for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
+ BroadcastRecord br = mParallelBroadcasts.get(i);
+ if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
+ continue;
+ }
+ if (!printed) {
+ if (needSep) {
+ pw.println();
+ }
+ needSep = true;
+ printed = true;
+ pw.println(" Active broadcasts [" + mQueueName + "]:");
+ }
+ pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
+ br.dump(pw, " ", sdf);
+ }
+
+ mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf);
+
+ if (dumpPackage == null || (mPendingBroadcast != null
+ && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
+ pw.println();
+ pw.println(" Pending broadcast [" + mQueueName + "]:");
+ if (mPendingBroadcast != null) {
+ mPendingBroadcast.dump(pw, " ", sdf);
+ } else {
+ pw.println(" (null)");
+ }
+ needSep = true;
+ }
+ }
+
+ mConstants.dump(pw);
+
+ int i;
+ boolean printed = false;
+
+ i = -1;
+ int lastIndex = mHistoryNext;
+ int ringIndex = lastIndex;
+ do {
+ // increasing index = more recent entry, and we want to print the most
+ // recent first and work backwards, so we roll through the ring backwards.
+ ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
+ BroadcastRecord r = mBroadcastHistory[ringIndex];
+ if (r == null) {
+ continue;
+ }
+
+ i++; // genuine record of some sort even if we're filtering it out
+ if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
+ continue;
+ }
+ if (!printed) {
+ if (needSep) {
+ pw.println();
+ }
+ needSep = true;
+ pw.println(" Historical broadcasts [" + mQueueName + "]:");
+ printed = true;
+ }
+ if (dumpAll) {
+ pw.print(" Historical Broadcast " + mQueueName + " #");
+ pw.print(i); pw.println(":");
+ r.dump(pw, " ", sdf);
+ } else {
+ pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
+ pw.print(" ");
+ pw.println(r.intent.toShortString(false, true, true, false));
+ if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
+ pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
+ }
+ Bundle bundle = r.intent.getExtras();
+ if (bundle != null) {
+ pw.print(" extras: "); pw.println(bundle.toString());
+ }
+ }
+ } while (ringIndex != lastIndex);
+
+ if (dumpPackage == null) {
+ lastIndex = ringIndex = mSummaryHistoryNext;
+ if (dumpAll) {
+ printed = false;
+ i = -1;
+ } else {
+ // roll over the 'i' full dumps that have already been issued
+ for (int j = i;
+ j > 0 && ringIndex != lastIndex;) {
+ ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
+ BroadcastRecord r = mBroadcastHistory[ringIndex];
+ if (r == null) {
+ continue;
+ }
+ j--;
+ }
+ }
+ // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
+ // the overall broadcast history.
+ do {
+ ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
+ Intent intent = mBroadcastSummaryHistory[ringIndex];
+ if (intent == null) {
+ continue;
+ }
+ if (!printed) {
+ if (needSep) {
+ pw.println();
+ }
+ needSep = true;
+ pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
+ printed = true;
+ }
+ if (!dumpAll && i >= 50) {
+ pw.println(" ...");
+ break;
+ }
+ i++;
+ pw.print(" #"); pw.print(i); pw.print(": ");
+ pw.println(intent.toShortString(false, true, true, false));
+ pw.print(" ");
+ TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
+ - mSummaryHistoryEnqueueTime[ringIndex], pw);
+ pw.print(" dispatch ");
+ TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
+ - mSummaryHistoryDispatchTime[ringIndex], pw);
+ pw.println(" finish");
+ pw.print(" enq=");
+ pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
+ pw.print(" disp=");
+ pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
+ pw.print(" fin=");
+ pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
+ Bundle bundle = intent.getExtras();
+ if (bundle != null) {
+ pw.print(" extras: "); pw.println(bundle.toString());
+ }
+ } while (ringIndex != lastIndex);
+ }
+
+ return needSep;
+ }
+}
diff --git a/services/core/java/com/android/server/am/BroadcastSkipPolicy.java b/services/core/java/com/android/server/am/BroadcastSkipPolicy.java
new file mode 100644
index 000000000000..9569848cbe37
--- /dev/null
+++ b/services/core/java/com/android/server/am/BroadcastSkipPolicy.java
@@ -0,0 +1,715 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.am;
+
+import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
+import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
+import static com.android.server.am.ActivityManagerService.checkComponentPermission;
+import static com.android.server.am.BroadcastQueue.TAG;
+
+import android.annotation.NonNull;
+import android.app.ActivityManager;
+import android.app.AppGlobals;
+import android.app.AppOpsManager;
+import android.app.BroadcastOptions;
+import android.app.PendingIntent;
+import android.content.ComponentName;
+import android.content.IIntentSender;
+import android.content.Intent;
+import android.content.IntentSender;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PermissionInfo;
+import android.content.pm.ResolveInfo;
+import android.os.Bundle;
+import android.os.Process;
+import android.os.RemoteException;
+import android.os.UserHandle;
+import android.permission.IPermissionManager;
+import android.util.Slog;
+
+import com.android.internal.util.ArrayUtils;
+
+/**
+ * Policy logic that decides if delivery of a particular {@link BroadcastRecord}
+ * should be skipped for a given {@link ResolveInfo} or {@link BroadcastFilter}.
+ * <p>
+ * This policy should be consulted as close as possible to the actual dispatch.
+ */
+public class BroadcastSkipPolicy {
+ private final ActivityManagerService mService;
+
+ public BroadcastSkipPolicy(ActivityManagerService service) {
+ mService = service;
+ }
+
+ /**
+ * Determine if the given {@link BroadcastRecord} is eligible to be sent to
+ * the given {@link ResolveInfo}.
+ */
+ public boolean shouldSkip(@NonNull BroadcastRecord r, @NonNull ResolveInfo info) {
+ final BroadcastOptions brOptions = r.options;
+ final ComponentName component = new ComponentName(
+ info.activityInfo.applicationInfo.packageName,
+ info.activityInfo.name);
+
+ if (brOptions != null &&
+ (info.activityInfo.applicationInfo.targetSdkVersion
+ < brOptions.getMinManifestReceiverApiLevel() ||
+ info.activityInfo.applicationInfo.targetSdkVersion
+ > brOptions.getMaxManifestReceiverApiLevel())) {
+ Slog.w(TAG, "Target SDK mismatch: receiver " + info.activityInfo
+ + " targets " + info.activityInfo.applicationInfo.targetSdkVersion
+ + " but delivery restricted to ["
+ + brOptions.getMinManifestReceiverApiLevel() + ", "
+ + brOptions.getMaxManifestReceiverApiLevel()
+ + "] broadcasting " + broadcastDescription(r, component));
+ return true;
+ }
+ if (brOptions != null &&
+ !brOptions.testRequireCompatChange(info.activityInfo.applicationInfo.uid)) {
+ Slog.w(TAG, "Compat change filtered: broadcasting " + broadcastDescription(r, component)
+ + " to uid " + info.activityInfo.applicationInfo.uid + " due to compat change "
+ + r.options.getRequireCompatChangeId());
+ return true;
+ }
+ if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
+ component.getPackageName(), info.activityInfo.applicationInfo.uid)) {
+ Slog.w(TAG, "Association not allowed: broadcasting "
+ + broadcastDescription(r, component));
+ return true;
+ }
+ if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
+ r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid)) {
+ Slog.w(TAG, "Firewall blocked: broadcasting "
+ + broadcastDescription(r, component));
+ return true;
+ }
+ int perm = checkComponentPermission(info.activityInfo.permission,
+ r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
+ info.activityInfo.exported);
+ if (perm != PackageManager.PERMISSION_GRANTED) {
+ if (!info.activityInfo.exported) {
+ Slog.w(TAG, "Permission Denial: broadcasting "
+ + broadcastDescription(r, component)
+ + " is not exported from uid " + info.activityInfo.applicationInfo.uid);
+ } else {
+ Slog.w(TAG, "Permission Denial: broadcasting "
+ + broadcastDescription(r, component)
+ + " requires " + info.activityInfo.permission);
+ }
+ return true;
+ } else if (info.activityInfo.permission != null) {
+ final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
+ if (opCode != AppOpsManager.OP_NONE && mService.getAppOpsManager().noteOpNoThrow(opCode,
+ r.callingUid, r.callerPackage, r.callerFeatureId,
+ "Broadcast delivered to " + info.activityInfo.name)
+ != AppOpsManager.MODE_ALLOWED) {
+ Slog.w(TAG, "Appop Denial: broadcasting "
+ + broadcastDescription(r, component)
+ + " requires appop " + AppOpsManager.permissionToOp(
+ info.activityInfo.permission));
+ return true;
+ }
+ }
+
+ boolean isSingleton = false;
+ try {
+ isSingleton = mService.isSingleton(info.activityInfo.processName,
+ info.activityInfo.applicationInfo,
+ info.activityInfo.name, info.activityInfo.flags);
+ } catch (SecurityException e) {
+ Slog.w(TAG, e.getMessage());
+ return true;
+ }
+ if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
+ if (ActivityManager.checkUidPermission(
+ android.Manifest.permission.INTERACT_ACROSS_USERS,
+ info.activityInfo.applicationInfo.uid)
+ != PackageManager.PERMISSION_GRANTED) {
+ Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
+ + " requests FLAG_SINGLE_USER, but app does not hold "
+ + android.Manifest.permission.INTERACT_ACROSS_USERS);
+ return true;
+ }
+ }
+ if (info.activityInfo.applicationInfo.isInstantApp()
+ && r.callingUid != info.activityInfo.applicationInfo.uid) {
+ Slog.w(TAG, "Instant App Denial: receiving "
+ + r.intent
+ + " to " + component.flattenToShortString()
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")"
+ + " Instant Apps do not support manifest receivers");
+ return true;
+ }
+ if (r.callerInstantApp
+ && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
+ && r.callingUid != info.activityInfo.applicationInfo.uid) {
+ Slog.w(TAG, "Instant App Denial: receiving "
+ + r.intent
+ + " to " + component.flattenToShortString()
+ + " requires receiver have visibleToInstantApps set"
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+ if (r.curApp != null && r.curApp.mErrorState.isCrashing()) {
+ // If the target process is crashing, just skip it.
+ Slog.w(TAG, "Skipping deliver ordered [" + r.queue.toString() + "] " + r
+ + " to " + r.curApp + ": process crashing");
+ return true;
+ }
+
+ boolean isAvailable = false;
+ try {
+ isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
+ info.activityInfo.packageName,
+ UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
+ } catch (Exception e) {
+ // all such failures mean we skip this receiver
+ Slog.w(TAG, "Exception getting recipient info for "
+ + info.activityInfo.packageName, e);
+ }
+ if (!isAvailable) {
+ Slog.w(TAG,
+ "Skipping delivery to " + info.activityInfo.packageName + " / "
+ + info.activityInfo.applicationInfo.uid
+ + " : package no longer available");
+ return true;
+ }
+
+ // If permissions need a review before any of the app components can run, we drop
+ // the broadcast and if the calling app is in the foreground and the broadcast is
+ // explicit we launch the review UI passing it a pending intent to send the skipped
+ // broadcast.
+ if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
+ info.activityInfo.packageName, UserHandle.getUserId(
+ info.activityInfo.applicationInfo.uid))) {
+ Slog.w(TAG,
+ "Skipping delivery: permission review required for "
+ + broadcastDescription(r, component));
+ return true;
+ }
+
+ // This is safe to do even if we are skipping the broadcast, and we need
+ // this information now to evaluate whether it is going to be allowed to run.
+ final int receiverUid = info.activityInfo.applicationInfo.uid;
+ // If it's a singleton, it needs to be the same app or a special app
+ if (r.callingUid != Process.SYSTEM_UID && isSingleton
+ && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
+ info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
+ }
+
+ final int allowed = mService.getAppStartModeLOSP(
+ info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
+ info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
+ if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
+ // We won't allow this receiver to be launched if the app has been
+ // completely disabled from launches, or it was not explicitly sent
+ // to it and the app is in a state that should not receive it
+ // (depending on how getAppStartModeLOSP has determined that).
+ if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
+ Slog.w(TAG, "Background execution disabled: receiving "
+ + r.intent + " to "
+ + component.flattenToShortString());
+ return true;
+ } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
+ || (r.intent.getComponent() == null
+ && r.intent.getPackage() == null
+ && ((r.intent.getFlags()
+ & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
+ && !isSignaturePerm(r.requiredPermissions))) {
+ mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
+ component.getPackageName());
+ Slog.w(TAG, "Background execution not allowed: receiving "
+ + r.intent + " to "
+ + component.flattenToShortString());
+ return true;
+ }
+ }
+
+ if (!Intent.ACTION_SHUTDOWN.equals(r.intent.getAction())
+ && !mService.mUserController
+ .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid),
+ 0 /* flags */)) {
+ Slog.w(TAG,
+ "Skipping delivery to " + info.activityInfo.packageName + " / "
+ + info.activityInfo.applicationInfo.uid + " : user is not running");
+ return true;
+ }
+
+ if (r.excludedPermissions != null && r.excludedPermissions.length > 0) {
+ for (int i = 0; i < r.excludedPermissions.length; i++) {
+ String excludedPermission = r.excludedPermissions[i];
+ try {
+ perm = AppGlobals.getPackageManager()
+ .checkPermission(excludedPermission,
+ info.activityInfo.applicationInfo.packageName,
+ UserHandle
+ .getUserId(info.activityInfo.applicationInfo.uid));
+ } catch (RemoteException e) {
+ perm = PackageManager.PERMISSION_DENIED;
+ }
+
+ int appOp = AppOpsManager.permissionToOpCode(excludedPermission);
+ if (appOp != AppOpsManager.OP_NONE) {
+ // When there is an app op associated with the permission,
+ // skip when both the permission and the app op are
+ // granted.
+ if ((perm == PackageManager.PERMISSION_GRANTED) && (
+ mService.getAppOpsManager().checkOpNoThrow(appOp,
+ info.activityInfo.applicationInfo.uid,
+ info.activityInfo.packageName)
+ == AppOpsManager.MODE_ALLOWED)) {
+ return true;
+ }
+ } else {
+ // When there is no app op associated with the permission,
+ // skip when permission is granted.
+ if (perm == PackageManager.PERMISSION_GRANTED) {
+ return true;
+ }
+ }
+ }
+ }
+
+ // Check that the receiver does *not* belong to any of the excluded packages
+ if (r.excludedPackages != null && r.excludedPackages.length > 0) {
+ if (ArrayUtils.contains(r.excludedPackages, component.getPackageName())) {
+ Slog.w(TAG, "Skipping delivery of excluded package "
+ + r.intent + " to "
+ + component.flattenToShortString()
+ + " excludes package " + component.getPackageName()
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+ }
+
+ if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
+ r.requiredPermissions != null && r.requiredPermissions.length > 0) {
+ for (int i = 0; i < r.requiredPermissions.length; i++) {
+ String requiredPermission = r.requiredPermissions[i];
+ try {
+ perm = AppGlobals.getPackageManager().
+ checkPermission(requiredPermission,
+ info.activityInfo.applicationInfo.packageName,
+ UserHandle
+ .getUserId(info.activityInfo.applicationInfo.uid));
+ } catch (RemoteException e) {
+ perm = PackageManager.PERMISSION_DENIED;
+ }
+ if (perm != PackageManager.PERMISSION_GRANTED) {
+ Slog.w(TAG, "Permission Denial: receiving "
+ + r.intent + " to "
+ + component.flattenToShortString()
+ + " requires " + requiredPermission
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+ int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
+ if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp) {
+ if (!noteOpForManifestReceiver(appOp, r, info, component)) {
+ return true;
+ }
+ }
+ }
+ }
+ if (r.appOp != AppOpsManager.OP_NONE) {
+ if (!noteOpForManifestReceiver(r.appOp, r, info, component)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the given {@link BroadcastRecord} is eligible to be sent to
+ * the given {@link BroadcastFilter}.
+ */
+ public boolean shouldSkip(@NonNull BroadcastRecord r, @NonNull BroadcastFilter filter) {
+ if (r.options != null && !r.options.testRequireCompatChange(filter.owningUid)) {
+ Slog.w(TAG, "Compat change filtered: broadcasting " + r.intent.toString()
+ + " to uid " + filter.owningUid + " due to compat change "
+ + r.options.getRequireCompatChangeId());
+ return true;
+ }
+ if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
+ filter.packageName, filter.owningUid)) {
+ Slog.w(TAG, "Association not allowed: broadcasting "
+ + r.intent.toString()
+ + " from " + r.callerPackage + " (pid=" + r.callingPid
+ + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
+ + filter);
+ return true;
+ }
+ if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
+ r.callingPid, r.resolvedType, filter.receiverList.uid)) {
+ Slog.w(TAG, "Firewall blocked: broadcasting "
+ + r.intent.toString()
+ + " from " + r.callerPackage + " (pid=" + r.callingPid
+ + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
+ + filter);
+ return true;
+ }
+ // Check that the sender has permission to send to this receiver
+ if (filter.requiredPermission != null) {
+ int perm = checkComponentPermission(filter.requiredPermission,
+ r.callingPid, r.callingUid, -1, true);
+ if (perm != PackageManager.PERMISSION_GRANTED) {
+ Slog.w(TAG, "Permission Denial: broadcasting "
+ + r.intent.toString()
+ + " from " + r.callerPackage + " (pid="
+ + r.callingPid + ", uid=" + r.callingUid + ")"
+ + " requires " + filter.requiredPermission
+ + " due to registered receiver " + filter);
+ return true;
+ } else {
+ final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
+ if (opCode != AppOpsManager.OP_NONE
+ && mService.getAppOpsManager().noteOpNoThrow(opCode, r.callingUid,
+ r.callerPackage, r.callerFeatureId, "Broadcast sent to protected receiver")
+ != AppOpsManager.MODE_ALLOWED) {
+ Slog.w(TAG, "Appop Denial: broadcasting "
+ + r.intent.toString()
+ + " from " + r.callerPackage + " (pid="
+ + r.callingPid + ", uid=" + r.callingUid + ")"
+ + " requires appop " + AppOpsManager.permissionToOp(
+ filter.requiredPermission)
+ + " due to registered receiver " + filter);
+ return true;
+ }
+ }
+ }
+
+ if ((filter.receiverList.app == null || filter.receiverList.app.isKilled()
+ || filter.receiverList.app.mErrorState.isCrashing())) {
+ Slog.w(TAG, "Skipping deliver [" + r.queue.toString() + "] " + r
+ + " to " + filter.receiverList + ": process gone or crashing");
+ return true;
+ }
+
+ // Ensure that broadcasts are only sent to other Instant Apps if they are marked as
+ // visible to Instant Apps.
+ final boolean visibleToInstantApps =
+ (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
+
+ if (!visibleToInstantApps && filter.instantApp
+ && filter.receiverList.uid != r.callingUid) {
+ Slog.w(TAG, "Instant App Denial: receiving "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")"
+ + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS");
+ return true;
+ }
+
+ if (!filter.visibleToInstantApp && r.callerInstantApp
+ && filter.receiverList.uid != r.callingUid) {
+ Slog.w(TAG, "Instant App Denial: receiving "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " requires receiver be visible to instant apps"
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+
+ // Check that the receiver has the required permission(s) to receive this broadcast.
+ if (r.requiredPermissions != null && r.requiredPermissions.length > 0) {
+ for (int i = 0; i < r.requiredPermissions.length; i++) {
+ String requiredPermission = r.requiredPermissions[i];
+ int perm = checkComponentPermission(requiredPermission,
+ filter.receiverList.pid, filter.receiverList.uid, -1, true);
+ if (perm != PackageManager.PERMISSION_GRANTED) {
+ Slog.w(TAG, "Permission Denial: receiving "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " requires " + requiredPermission
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+ int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
+ if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
+ && mService.getAppOpsManager().noteOpNoThrow(appOp,
+ filter.receiverList.uid, filter.packageName, filter.featureId,
+ "Broadcast delivered to registered receiver " + filter.receiverId)
+ != AppOpsManager.MODE_ALLOWED) {
+ Slog.w(TAG, "Appop Denial: receiving "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " requires appop " + AppOpsManager.permissionToOp(
+ requiredPermission)
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+ }
+ }
+ if ((r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
+ int perm = checkComponentPermission(null,
+ filter.receiverList.pid, filter.receiverList.uid, -1, true);
+ if (perm != PackageManager.PERMISSION_GRANTED) {
+ Slog.w(TAG, "Permission Denial: security check failed when receiving "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+ }
+ // Check that the receiver does *not* have any excluded permissions
+ if (r.excludedPermissions != null && r.excludedPermissions.length > 0) {
+ for (int i = 0; i < r.excludedPermissions.length; i++) {
+ String excludedPermission = r.excludedPermissions[i];
+ final int perm = checkComponentPermission(excludedPermission,
+ filter.receiverList.pid, filter.receiverList.uid, -1, true);
+
+ int appOp = AppOpsManager.permissionToOpCode(excludedPermission);
+ if (appOp != AppOpsManager.OP_NONE) {
+ // When there is an app op associated with the permission,
+ // skip when both the permission and the app op are
+ // granted.
+ if ((perm == PackageManager.PERMISSION_GRANTED) && (
+ mService.getAppOpsManager().checkOpNoThrow(appOp,
+ filter.receiverList.uid,
+ filter.packageName)
+ == AppOpsManager.MODE_ALLOWED)) {
+ Slog.w(TAG, "Appop Denial: receiving "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " excludes appop " + AppOpsManager.permissionToOp(
+ excludedPermission)
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+ } else {
+ // When there is no app op associated with the permission,
+ // skip when permission is granted.
+ if (perm == PackageManager.PERMISSION_GRANTED) {
+ Slog.w(TAG, "Permission Denial: receiving "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " excludes " + excludedPermission
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+ }
+ }
+ }
+
+ // Check that the receiver does *not* belong to any of the excluded packages
+ if (r.excludedPackages != null && r.excludedPackages.length > 0) {
+ if (ArrayUtils.contains(r.excludedPackages, filter.packageName)) {
+ Slog.w(TAG, "Skipping delivery of excluded package "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " excludes package " + filter.packageName
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+ }
+
+ // If the broadcast also requires an app op check that as well.
+ if (r.appOp != AppOpsManager.OP_NONE
+ && mService.getAppOpsManager().noteOpNoThrow(r.appOp,
+ filter.receiverList.uid, filter.packageName, filter.featureId,
+ "Broadcast delivered to registered receiver " + filter.receiverId)
+ != AppOpsManager.MODE_ALLOWED) {
+ Slog.w(TAG, "Appop Denial: receiving "
+ + r.intent.toString()
+ + " to " + filter.receiverList.app
+ + " (pid=" + filter.receiverList.pid
+ + ", uid=" + filter.receiverList.uid + ")"
+ + " requires appop " + AppOpsManager.opToName(r.appOp)
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return true;
+ }
+
+ // Ensure that broadcasts are only sent to other apps if they are explicitly marked as
+ // exported, or are System level broadcasts
+ if (!filter.exported && checkComponentPermission(null, r.callingPid,
+ r.callingUid, filter.receiverList.uid, filter.exported)
+ != PackageManager.PERMISSION_GRANTED) {
+ Slog.w(TAG, "Exported Denial: sending "
+ + r.intent.toString()
+ + ", action: " + r.intent.getAction()
+ + " from " + r.callerPackage
+ + " (uid=" + r.callingUid + ")"
+ + " due to receiver " + filter.receiverList.app
+ + " (uid " + filter.receiverList.uid + ")"
+ + " not specifying RECEIVER_EXPORTED");
+ return true;
+ }
+
+ // If permissions need a review before any of the app components can run, we drop
+ // the broadcast and if the calling app is in the foreground and the broadcast is
+ // explicit we launch the review UI passing it a pending intent to send the skipped
+ // broadcast.
+ if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
+ filter.owningUserId)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ private static String broadcastDescription(BroadcastRecord r, ComponentName component) {
+ return r.intent.toString()
+ + " from " + r.callerPackage + " (pid=" + r.callingPid
+ + ", uid=" + r.callingUid + ") to " + component.flattenToShortString();
+ }
+
+ private boolean noteOpForManifestReceiver(int appOp, BroadcastRecord r, ResolveInfo info,
+ ComponentName component) {
+ if (ArrayUtils.isEmpty(info.activityInfo.attributionTags)) {
+ return noteOpForManifestReceiverInner(appOp, r, info, component, null);
+ } else {
+ // Attribution tags provided, noteOp each tag
+ for (String tag : info.activityInfo.attributionTags) {
+ if (!noteOpForManifestReceiverInner(appOp, r, info, component, tag)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+
+ private boolean noteOpForManifestReceiverInner(int appOp, BroadcastRecord r, ResolveInfo info,
+ ComponentName component, String tag) {
+ if (mService.getAppOpsManager().noteOpNoThrow(appOp,
+ info.activityInfo.applicationInfo.uid,
+ info.activityInfo.packageName,
+ tag,
+ "Broadcast delivered to " + info.activityInfo.name)
+ != AppOpsManager.MODE_ALLOWED) {
+ Slog.w(TAG, "Appop Denial: receiving "
+ + r.intent + " to "
+ + component.flattenToShortString()
+ + " requires appop " + AppOpsManager.opToName(appOp)
+ + " due to sender " + r.callerPackage
+ + " (uid " + r.callingUid + ")");
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Return true if all given permissions are signature-only perms.
+ */
+ private boolean isSignaturePerm(String[] perms) {
+ if (perms == null) {
+ return false;
+ }
+ IPermissionManager pm = AppGlobals.getPermissionManager();
+ for (int i = perms.length-1; i >= 0; i--) {
+ try {
+ PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
+ if (pi == null) {
+ // a required permission that no package has actually
+ // defined cannot be signature-required.
+ return false;
+ }
+ if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
+ | PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
+ != PermissionInfo.PROTECTION_SIGNATURE) {
+ // If this a signature permission and NOT allowed for privileged apps, it
+ // is okay... otherwise, nope!
+ return false;
+ }
+ } catch (RemoteException e) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean requestStartTargetPermissionsReviewIfNeededLocked(
+ BroadcastRecord receiverRecord, String receivingPackageName,
+ final int receivingUserId) {
+ if (!mService.getPackageManagerInternal().isPermissionsReviewRequired(
+ receivingPackageName, receivingUserId)) {
+ return true;
+ }
+
+ final boolean callerForeground = receiverRecord.callerApp != null
+ ? receiverRecord.callerApp.mState.getSetSchedGroup()
+ != ProcessList.SCHED_GROUP_BACKGROUND : true;
+
+ // Show a permission review UI only for explicit broadcast from a foreground app
+ if (callerForeground && receiverRecord.intent.getComponent() != null) {
+ IIntentSender target = mService.mPendingIntentController.getIntentSender(
+ ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
+ receiverRecord.callerFeatureId, receiverRecord.callingUid,
+ receiverRecord.userId, null, null, 0,
+ new Intent[]{receiverRecord.intent},
+ new String[]{receiverRecord.intent.resolveType(mService.mContext
+ .getContentResolver())},
+ PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
+ | PendingIntent.FLAG_IMMUTABLE, null);
+
+ final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
+ | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
+ | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
+ intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
+ intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
+
+ if (DEBUG_PERMISSIONS_REVIEW) {
+ Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
+ + receivingPackageName);
+ }
+
+ mService.mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
+ }
+ });
+ } else {
+ Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
+ + receivingPackageName + " requires a permissions review");
+ }
+
+ return false;
+ }
+}
diff --git a/services/core/java/com/android/server/audio/AudioDeviceBroker.java b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
index eba9c7a5f14e..e97d9c22620e 100644
--- a/services/core/java/com/android/server/audio/AudioDeviceBroker.java
+++ b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
@@ -1771,8 +1771,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
return;
}
Log.w(TAG, "Communication client died");
- removeCommunicationRouteClient(client.getBinder(), true);
- onUpdateCommunicationRouteClient("onCommunicationRouteClientDied");
+ setCommunicationRouteForClient(client.getBinder(), client.getPid(), null,
+ BtHelper.SCO_MODE_UNDEFINED, "onCommunicationRouteClientDied");
}
/**
diff --git a/services/core/java/com/android/server/biometrics/sensors/BiometricStateCallback.java b/services/core/java/com/android/server/biometrics/sensors/BiometricStateCallback.java
index f8543162f95e..2263e80039bd 100644
--- a/services/core/java/com/android/server/biometrics/sensors/BiometricStateCallback.java
+++ b/services/core/java/com/android/server/biometrics/sensors/BiometricStateCallback.java
@@ -28,6 +28,7 @@ import android.content.pm.UserInfo;
import android.hardware.biometrics.BiometricStateListener;
import android.hardware.biometrics.IBiometricStateListener;
import android.hardware.biometrics.SensorPropertiesInternal;
+import android.os.IBinder;
import android.os.RemoteException;
import android.os.UserManager;
import android.util.Slog;
@@ -45,7 +46,8 @@ import java.util.concurrent.CopyOnWriteArrayList;
* @param <P> internal property type
*/
public class BiometricStateCallback<T extends BiometricServiceProvider<P>,
- P extends SensorPropertiesInternal> implements ClientMonitorCallback {
+ P extends SensorPropertiesInternal>
+ implements ClientMonitorCallback, IBinder.DeathRecipient {
private static final String TAG = "BiometricStateCallback";
@@ -161,6 +163,11 @@ public class BiometricStateCallback<T extends BiometricServiceProvider<P>,
@NonNull IBiometricStateListener listener) {
mBiometricStateListeners.add(listener);
broadcastCurrentEnrollmentState(listener);
+ try {
+ listener.asBinder().linkToDeath(this, 0 /* flags */);
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Failed to link to death", e);
+ }
}
private synchronized void broadcastCurrentEnrollmentState(
@@ -196,4 +203,19 @@ public class BiometricStateCallback<T extends BiometricServiceProvider<P>,
Slog.e(TAG, "Remote exception", e);
}
}
-}
+
+ @Override
+ public void binderDied() {
+ // Do nothing, handled below
+ }
+
+ @Override
+ public void binderDied(IBinder who) {
+ Slog.w(TAG, "Callback binder died: " + who);
+ if (mBiometricStateListeners.removeIf(listener -> listener.asBinder().equals(who))) {
+ Slog.w(TAG, "Removed dead listener for " + who);
+ } else {
+ Slog.w(TAG, "No dead listeners found");
+ }
+ }
+} \ No newline at end of file
diff --git a/services/core/java/com/android/server/broadcastradio/hal2/RadioEventLogger.java b/services/core/java/com/android/server/broadcastradio/hal2/RadioEventLogger.java
new file mode 100644
index 000000000000..48112c452f02
--- /dev/null
+++ b/services/core/java/com/android/server/broadcastradio/hal2/RadioEventLogger.java
@@ -0,0 +1,44 @@
+/**
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.broadcastradio.hal2;
+
+import android.util.IndentingPrintWriter;
+import android.util.LocalLog;
+import android.util.Log;
+import android.util.Slog;
+
+final class RadioEventLogger {
+ private final String mTag;
+ private final LocalLog mEventLogger;
+
+ RadioEventLogger(String tag, int loggerQueueSize) {
+ mTag = tag;
+ mEventLogger = new LocalLog(loggerQueueSize);
+ }
+
+ void logRadioEvent(String logFormat, Object... args) {
+ String log = String.format(logFormat, args);
+ mEventLogger.log(log);
+ if (Log.isLoggable(mTag, Log.DEBUG)) {
+ Slog.d(mTag, log);
+ }
+ }
+
+ void dump(IndentingPrintWriter pw) {
+ mEventLogger.dump(pw);
+ }
+}
diff --git a/services/core/java/com/android/server/broadcastradio/hal2/RadioModule.java b/services/core/java/com/android/server/broadcastradio/hal2/RadioModule.java
index 852aa66866f0..0a23e385d67a 100644
--- a/services/core/java/com/android/server/broadcastradio/hal2/RadioModule.java
+++ b/services/core/java/com/android/server/broadcastradio/hal2/RadioModule.java
@@ -55,12 +55,14 @@ import java.util.stream.Collectors;
class RadioModule {
private static final String TAG = "BcRadio2Srv.module";
+ private static final int RADIO_EVENT_LOGGER_QUEUE_SIZE = 25;
@NonNull private final IBroadcastRadio mService;
@NonNull public final RadioManager.ModuleProperties mProperties;
private final Object mLock;
@NonNull private final Handler mHandler;
+ @NonNull private final RadioEventLogger mEventLogger;
@GuardedBy("mLock")
private ITunerSession mHalTunerSession;
@@ -138,6 +140,7 @@ class RadioModule {
mService = Objects.requireNonNull(service);
mLock = Objects.requireNonNull(lock);
mHandler = new Handler(Looper.getMainLooper());
+ mEventLogger = new RadioEventLogger(TAG, RADIO_EVENT_LOGGER_QUEUE_SIZE);
}
public static @Nullable RadioModule tryLoadingModule(int idx, @NonNull String fqName,
@@ -176,13 +179,14 @@ class RadioModule {
public @NonNull TunerSession openSession(@NonNull android.hardware.radio.ITunerCallback userCb)
throws RemoteException {
- Slog.i(TAG, "Open TunerSession");
+ mEventLogger.logRadioEvent("Open TunerSession");
synchronized (mLock) {
if (mHalTunerSession == null) {
Mutable<ITunerSession> hwSession = new Mutable<>();
mService.openSession(mHalTunerCallback, (result, session) -> {
Convert.throwOnError("openSession", result);
hwSession.value = session;
+ mEventLogger.logRadioEvent("New HIDL 2.0 tuner session is opened");
});
mHalTunerSession = Objects.requireNonNull(hwSession.value);
}
@@ -207,7 +211,7 @@ class RadioModule {
// Copy the contents of mAidlTunerSessions into a local array because TunerSession.close()
// must be called without mAidlTunerSessions locked because it can call
// onTunerSessionClosed().
- Slog.i(TAG, "Close TunerSessions");
+ mEventLogger.logRadioEvent("Close TunerSessions");
TunerSession[] tunerSessions;
synchronized (mLock) {
tunerSessions = new TunerSession[mAidlTunerSessions.size()];
@@ -320,7 +324,7 @@ class RadioModule {
}
onTunerSessionProgramListFilterChanged(null);
if (mAidlTunerSessions.isEmpty() && mHalTunerSession != null) {
- Slog.i(TAG, "Closing HAL tuner session");
+ mEventLogger.logRadioEvent("Closing HAL tuner session");
try {
mHalTunerSession.close();
} catch (RemoteException ex) {
@@ -372,7 +376,7 @@ class RadioModule {
public android.hardware.radio.ICloseHandle addAnnouncementListener(@NonNull int[] enabledTypes,
@NonNull android.hardware.radio.IAnnouncementListener listener) throws RemoteException {
- Slog.i(TAG, "Add AnnouncementListener");
+ mEventLogger.logRadioEvent("Add AnnouncementListener");
ArrayList<Byte> enabledList = new ArrayList<>();
for (int type : enabledTypes) {
enabledList.add((byte)type);
@@ -409,7 +413,7 @@ class RadioModule {
}
Bitmap getImage(int id) {
- Slog.i(TAG, "Get image for id " + id);
+ mEventLogger.logRadioEvent("Get image for id %d", id);
if (id == 0) throw new IllegalArgumentException("Image ID is missing");
byte[] rawImage;
@@ -449,6 +453,10 @@ class RadioModule {
}
pw.decreaseIndent();
}
+ pw.printf("Radio module events:\n");
+ pw.increaseIndent();
+ mEventLogger.dump(pw);
+ pw.decreaseIndent();
pw.decreaseIndent();
}
}
diff --git a/services/core/java/com/android/server/broadcastradio/hal2/TunerSession.java b/services/core/java/com/android/server/broadcastradio/hal2/TunerSession.java
index 41f753c11216..918dc98e3a9e 100644
--- a/services/core/java/com/android/server/broadcastradio/hal2/TunerSession.java
+++ b/services/core/java/com/android/server/broadcastradio/hal2/TunerSession.java
@@ -28,7 +28,6 @@ import android.hardware.radio.ProgramSelector;
import android.hardware.radio.RadioManager;
import android.os.RemoteException;
import android.util.IndentingPrintWriter;
-import android.util.Log;
import android.util.MutableBoolean;
import android.util.MutableInt;
import android.util.Slog;
@@ -41,8 +40,10 @@ import java.util.Objects;
class TunerSession extends ITuner.Stub {
private static final String TAG = "BcRadio2Srv.session";
private static final String kAudioDeviceName = "Radio tuner source";
+ private static final int TUNER_EVENT_LOGGER_QUEUE_SIZE = 25;
private final Object mLock;
+ @NonNull private final RadioEventLogger mEventLogger;
private final RadioModule mModule;
private final ITunerSession mHwSession;
@@ -61,15 +62,12 @@ class TunerSession extends ITuner.Stub {
mHwSession = Objects.requireNonNull(hwSession);
mCallback = Objects.requireNonNull(callback);
mLock = Objects.requireNonNull(lock);
- }
-
- private boolean isDebugEnabled() {
- return Log.isLoggable(TAG, Log.DEBUG);
+ mEventLogger = new RadioEventLogger(TAG, TUNER_EVENT_LOGGER_QUEUE_SIZE);
}
@Override
public void close() {
- if (isDebugEnabled()) Slog.d(TAG, "Close");
+ mEventLogger.logRadioEvent("Close");
close(null);
}
@@ -81,7 +79,7 @@ class TunerSession extends ITuner.Stub {
* @param error Optional error to send to client before session is closed.
*/
public void close(@Nullable Integer error) {
- if (isDebugEnabled()) Slog.d(TAG, "Close on error " + error);
+ mEventLogger.logRadioEvent("Close on error %d", error);
synchronized (mLock) {
if (mIsClosed) return;
if (error != null) {
@@ -145,10 +143,8 @@ class TunerSession extends ITuner.Stub {
@Override
public void step(boolean directionDown, boolean skipSubChannel) throws RemoteException {
- if (isDebugEnabled()) {
- Slog.d(TAG, "Step with directionDown " + directionDown
- + " skipSubChannel " + skipSubChannel);
- }
+ mEventLogger.logRadioEvent("Step with direction %s, skipSubChannel? %s",
+ directionDown ? "down" : "up", skipSubChannel ? "yes" : "no");
synchronized (mLock) {
checkNotClosedLocked();
int halResult = mHwSession.step(!directionDown);
@@ -158,10 +154,8 @@ class TunerSession extends ITuner.Stub {
@Override
public void scan(boolean directionDown, boolean skipSubChannel) throws RemoteException {
- if (isDebugEnabled()) {
- Slog.d(TAG, "Scan with directionDown " + directionDown
- + " skipSubChannel " + skipSubChannel);
- }
+ mEventLogger.logRadioEvent("Scan with direction %s, skipSubChannel? %s",
+ directionDown ? "down" : "up", skipSubChannel ? "yes" : "no");
synchronized (mLock) {
checkNotClosedLocked();
int halResult = mHwSession.scan(!directionDown, skipSubChannel);
@@ -171,7 +165,7 @@ class TunerSession extends ITuner.Stub {
@Override
public void tune(ProgramSelector selector) throws RemoteException {
- if (isDebugEnabled()) Slog.d(TAG, "Tune with selector " + selector);
+ mEventLogger.logRadioEvent("Tune with selector %s", selector);
synchronized (mLock) {
checkNotClosedLocked();
int halResult = mHwSession.tune(Convert.programSelectorToHal(selector));
@@ -195,7 +189,7 @@ class TunerSession extends ITuner.Stub {
@Override
public Bitmap getImage(int id) {
- if (isDebugEnabled()) Slog.d(TAG, "Get image for " + id);
+ mEventLogger.logRadioEvent("Get image for %d", id);
return mModule.getImage(id);
}
@@ -208,7 +202,7 @@ class TunerSession extends ITuner.Stub {
@Override
public void startProgramListUpdates(ProgramList.Filter filter) throws RemoteException {
- if (isDebugEnabled()) Slog.d(TAG, "start programList updates " + filter);
+ mEventLogger.logRadioEvent("start programList updates %s", filter);
// If the AIDL client provides a null filter, it wants all updates, so use the most broad
// filter.
if (filter == null) {
@@ -267,7 +261,7 @@ class TunerSession extends ITuner.Stub {
@Override
public void stopProgramListUpdates() throws RemoteException {
- if (isDebugEnabled()) Slog.d(TAG, "Stop programList updates");
+ mEventLogger.logRadioEvent("Stop programList updates");
synchronized (mLock) {
checkNotClosedLocked();
mProgramInfoCache = null;
@@ -291,7 +285,7 @@ class TunerSession extends ITuner.Stub {
@Override
public boolean isConfigFlagSet(int flag) {
- if (isDebugEnabled()) Slog.d(TAG, "Is ConfigFlagSet for " + ConfigFlag.toString(flag));
+ mEventLogger.logRadioEvent("Is ConfigFlagSet for %s", ConfigFlag.toString(flag));
synchronized (mLock) {
checkNotClosedLocked();
@@ -313,9 +307,7 @@ class TunerSession extends ITuner.Stub {
@Override
public void setConfigFlag(int flag, boolean value) throws RemoteException {
- if (isDebugEnabled()) {
- Slog.d(TAG, "Set ConfigFlag " + ConfigFlag.toString(flag) + " = " + value);
- }
+ mEventLogger.logRadioEvent("Set ConfigFlag %s = %b", ConfigFlag.toString(flag), value);
synchronized (mLock) {
checkNotClosedLocked();
int halResult = mHwSession.setConfigFlag(flag, value);
@@ -351,6 +343,10 @@ class TunerSession extends ITuner.Stub {
pw.printf("ProgramInfoCache: %s\n", mProgramInfoCache);
pw.printf("Config: %s\n", mDummyConfig);
}
+ pw.printf("Tuner session events:\n");
+ pw.increaseIndent();
+ mEventLogger.dump(pw);
+ pw.decreaseIndent();
pw.decreaseIndent();
}
}
diff --git a/services/core/java/com/android/server/camera/CameraServiceProxy.java b/services/core/java/com/android/server/camera/CameraServiceProxy.java
index 66ef5e761194..11eb78277beb 100644
--- a/services/core/java/com/android/server/camera/CameraServiceProxy.java
+++ b/services/core/java/com/android/server/camera/CameraServiceProxy.java
@@ -582,13 +582,18 @@ public class CameraServiceProxy extends SystemService
}
@Override
- public boolean isCameraDisabled() {
+ public boolean isCameraDisabled(int userId) {
DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
if (dpm == null) {
Slog.e(TAG, "Failed to get the device policy manager service");
return false;
}
- return dpm.getCameraDisabled(null);
+ try {
+ return dpm.getCameraDisabled(null, userId);
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
}
};
diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java
index 931c692b5f01..b4e91b586b40 100644
--- a/services/core/java/com/android/server/connectivity/Vpn.java
+++ b/services/core/java/com/android/server/connectivity/Vpn.java
@@ -1110,7 +1110,7 @@ public class Vpn {
// Except for Settings and VpnDialogs, the caller should be matched one of oldPackage or
// newPackage. Otherwise, non VPN owner might get the VPN always-on status of the VPN owner.
// See b/191382886.
- if (!hasControlVpnPermission()) {
+ if (mContext.checkCallingOrSelfPermission(CONTROL_VPN) != PERMISSION_GRANTED) {
if (oldPackage != null) {
verifyCallingUidAndPackage(oldPackage);
}
@@ -2073,10 +2073,6 @@ public class Vpn {
"Unauthorized Caller");
}
- private boolean hasControlVpnPermission() {
- return mContext.checkCallingOrSelfPermission(CONTROL_VPN) == PERMISSION_GRANTED;
- }
-
private class Connection implements ServiceConnection {
private IBinder mService;
@@ -3901,10 +3897,8 @@ public class Vpn {
Binder.restoreCallingIdentity(token);
}
- // If package has CONTROL_VPN, grant the ACTIVATE_PLATFORM_VPN appop.
- if (hasControlVpnPermission()) {
- setPackageAuthorization(packageName, VpnManager.TYPE_VPN_PLATFORM);
- }
+ // TODO: if package has CONTROL_VPN, grant the ACTIVATE_PLATFORM_VPN appop.
+ // This mirrors the prepareAndAuthorize that is used by VpnService.
// Return whether the app is already pre-consented
return isVpnProfilePreConsented(mContext, packageName);
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
index ea54b3001163..e6c2e7cae23e 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java
@@ -544,6 +544,7 @@ public class HdmiCecLocalDevicePlayback extends HdmiCecLocalDeviceSource {
|| message.getOpcode() == Constants.MESSAGE_SET_STREAM_PATH
|| message.getOpcode() == Constants.MESSAGE_ACTIVE_SOURCE) {
removeAction(ActiveSourceAction.class);
+ removeAction(OneTouchPlayAction.class);
return;
}
}
diff --git a/services/core/java/com/android/server/hdmi/HdmiControlService.java b/services/core/java/com/android/server/hdmi/HdmiControlService.java
index fa8b5c1b8086..3ee35036e9fd 100644
--- a/services/core/java/com/android/server/hdmi/HdmiControlService.java
+++ b/services/core/java/com/android/server/hdmi/HdmiControlService.java
@@ -1051,13 +1051,13 @@ public class HdmiControlService extends SystemService {
// Address allocation completed for all devices. Notify each device.
if (allocatingDevices.size() == ++finished[0]) {
- mAddressAllocated = true;
if (initiatedBy != INITIATED_BY_HOTPLUG) {
// In case of the hotplug we don't call
// onInitializeCecComplete()
// since we reallocate the logical address only.
onInitializeCecComplete(initiatedBy);
}
+ mAddressAllocated = true;
notifyAddressAllocated(allocatedDevices, initiatedBy);
// Reinvoke the saved display status callback once the local
// device is ready.
diff --git a/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java b/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java
index eb73234549c9..3e397468aa87 100644
--- a/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java
+++ b/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java
@@ -109,13 +109,11 @@ final class IInputMethodInvoker {
@AnyThread
void initializeInternal(IBinder token, IInputMethodPrivilegedOperations privilegedOperations,
- int configChanges, boolean stylusHandWritingSupported,
- @InputMethodNavButtonFlags int navigationBarFlags) {
+ int configChanges, @InputMethodNavButtonFlags int navigationBarFlags) {
final IInputMethod.InitParams params = new IInputMethod.InitParams();
params.token = token;
params.privilegedOperations = privilegedOperations;
params.configChanges = configChanges;
- params.stylusHandWritingSupported = stylusHandWritingSupported;
params.navigationBarFlags = navigationBarFlags;
try {
mTarget.initializeInternal(params);
@@ -279,4 +277,13 @@ final class IInputMethodInvoker {
logRemoteException(e);
}
}
+
+ @AnyThread
+ void removeStylusHandwritingWindow() {
+ try {
+ mTarget.removeStylusHandwritingWindow();
+ } catch (RemoteException e) {
+ logRemoteException(e);
+ }
+ }
}
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java b/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java
index b63592c2fedb..23ea39a3b022 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java
@@ -286,8 +286,7 @@ final class InputMethodBindingController {
if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken);
final InputMethodInfo info = mMethodMap.get(mSelectedMethodId);
mSupportsStylusHw = info.supportsStylusHandwriting();
- mService.initializeImeLocked(mCurMethod, mCurToken, info.getConfigChanges(),
- mSupportsStylusHw);
+ mService.initializeImeLocked(mCurMethod, mCurToken, info.getConfigChanges());
mService.scheduleNotifyImeUidToAudioService(mCurMethodUid);
mService.reRequestCurrentClientSessionLocked();
mService.performOnCreateInlineSuggestionsRequestLocked();
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
index 23f437392d2b..7bd835c73749 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
@@ -246,6 +246,7 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub
private static final int MSG_RESET_HANDWRITING = 1090;
private static final int MSG_START_HANDWRITING = 1100;
private static final int MSG_FINISH_HANDWRITING = 1110;
+ private static final int MSG_REMOVE_HANDWRITING_WINDOW = 1120;
private static final int MSG_SET_INTERACTIVE = 3030;
@@ -2719,13 +2720,13 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub
@GuardedBy("ImfLock.class")
void initializeImeLocked(@NonNull IInputMethodInvoker inputMethod, @NonNull IBinder token,
- @android.content.pm.ActivityInfo.Config int configChanges, boolean supportStylusHw) {
+ @android.content.pm.ActivityInfo.Config int configChanges) {
if (DEBUG) {
Slog.v(TAG, "Sending attach of token: " + token + " for display: "
+ mCurTokenDisplayId);
}
inputMethod.initializeInternal(token, new InputMethodPrivilegedOperationsImpl(this, token),
- configChanges, supportStylusHw, getInputMethodNavButtonFlagsLocked());
+ configChanges, getInputMethodNavButtonFlagsLocked());
}
@AnyThread
@@ -2734,6 +2735,11 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub
}
@AnyThread
+ void scheduleRemoveStylusHandwritingWindow() {
+ mHandler.obtainMessage(MSG_REMOVE_HANDWRITING_WINDOW).sendToTarget();
+ }
+
+ @AnyThread
void scheduleNotifyImeUidToAudioService(int uid) {
mHandler.removeMessages(MSG_NOTIFY_IME_UID_TO_AUDIO_SERVICE);
mHandler.obtainMessage(MSG_NOTIFY_IME_UID_TO_AUDIO_SERVICE, uid, 0 /* unused */)
@@ -4363,40 +4369,50 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub
private void add(int deviceId) {
synchronized (ImfLock.class) {
- if (mStylusIds == null) {
- mStylusIds = new IntArray();
- } else if (mStylusIds.indexOf(deviceId) != -1) {
- return;
- }
- Slog.d(TAG, "New Stylus device " + deviceId + " added.");
- mStylusIds.add(deviceId);
- // a new Stylus is detected. If IME supports handwriting and we don't have
- // handwriting initialized, lets do it now.
- if (!mHwController.getCurrentRequestId().isPresent()
- && mMethodMap.get(getSelectedMethodIdLocked())
- .supportsStylusHandwriting()) {
- scheduleResetStylusHandwriting();
- }
+ addStylusDeviceIdLocked(deviceId);
}
}
private void remove(int deviceId) {
synchronized (ImfLock.class) {
- if (mStylusIds == null || mStylusIds.size() == 0) {
- return;
- }
- if (mStylusIds.indexOf(deviceId) != -1) {
- mStylusIds.remove(deviceId);
- Slog.d(TAG, "Stylus device " + deviceId + " removed.");
- }
- if (mStylusIds.size() == 0) {
- mHwController.reset();
- }
+ removeStylusDeviceIdLocked(deviceId);
}
}
}, mHandler);
}
+ private void addStylusDeviceIdLocked(int deviceId) {
+ if (mStylusIds == null) {
+ mStylusIds = new IntArray();
+ } else if (mStylusIds.indexOf(deviceId) != -1) {
+ return;
+ }
+ Slog.d(TAG, "New Stylus deviceId" + deviceId + " added.");
+ mStylusIds.add(deviceId);
+ // a new Stylus is detected. If IME supports handwriting, and we don't have
+ // handwriting initialized, lets do it now.
+ if (!mHwController.getCurrentRequestId().isPresent()
+ && mBindingController.supportsStylusHandwriting()) {
+ scheduleResetStylusHandwriting();
+ }
+ }
+
+ private void removeStylusDeviceIdLocked(int deviceId) {
+ if (mStylusIds == null || mStylusIds.size() == 0) {
+ return;
+ }
+ int index;
+ if ((index = mStylusIds.indexOf(deviceId)) != -1) {
+ mStylusIds.remove(index);
+ Slog.d(TAG, "Stylus deviceId: " + deviceId + " removed.");
+ }
+ if (mStylusIds.size() == 0) {
+ // no more supported stylus(es) in system.
+ mHwController.reset();
+ scheduleRemoveStylusHandwritingWindow();
+ }
+ }
+
private static boolean isStylusDevice(InputDevice inputDevice) {
return inputDevice.supportsSource(InputDevice.SOURCE_STYLUS)
|| inputDevice.supportsSource(InputDevice.SOURCE_BLUETOOTH_STYLUS);
@@ -4422,17 +4438,8 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub
}
final long ident = Binder.clearCallingIdentity();
try {
- if (!mBindingController.supportsStylusHandwriting()) {
- Slog.w(TAG, "Stylus HW unsupported by IME. Ignoring addVirtualStylusId()");
- return;
- }
-
if (DEBUG) Slog.v(TAG, "Adding virtual stylus id for session");
- if (mStylusIds == null) {
- mStylusIds = new IntArray();
- }
- mStylusIds.add(VIRTUAL_STYLUS_ID_FOR_TEST);
- scheduleResetStylusHandwriting();
+ addStylusDeviceIdLocked(VIRTUAL_STYLUS_ID_FOR_TEST);
} finally {
Binder.restoreCallingIdentity(ident);
}
@@ -4441,10 +4448,7 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub
@GuardedBy("ImfLock.class")
private void removeVirtualStylusIdForTestSessionLocked() {
- int index;
- if ((index = mStylusIds.indexOf(VIRTUAL_STYLUS_ID_FOR_TEST)) != -1) {
- mStylusIds.remove(index);
- }
+ removeStylusDeviceIdLocked(VIRTUAL_STYLUS_ID_FOR_TEST);
}
private static IntArray getStylusInputDeviceIds(InputManager im) {
@@ -4922,6 +4926,14 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub
}
}
return true;
+ case MSG_REMOVE_HANDWRITING_WINDOW:
+ synchronized (ImfLock.class) {
+ IInputMethodInvoker curMethod = getCurMethodLocked();
+ if (curMethod != null) {
+ curMethod.removeStylusHandwritingWindow();
+ }
+ }
+ return true;
}
return false;
}
diff --git a/services/core/java/com/android/server/location/contexthub/ContextHubEventLogger.java b/services/core/java/com/android/server/location/contexthub/ContextHubEventLogger.java
new file mode 100644
index 000000000000..e46bb74003a2
--- /dev/null
+++ b/services/core/java/com/android/server/location/contexthub/ContextHubEventLogger.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.location.contexthub;
+
+import android.hardware.location.NanoAppMessage;
+
+/**
+ * A class to log events and useful metrics within the Context Hub service.
+ *
+ * The class holds a queue of the last NUM_EVENTS_TO_STORE events for each
+ * event category: nanoapp load, nanoapp unload, message from a nanoapp,
+ * message to a nanoapp, and context hub restarts. The dump() function
+ * will be called during debug dumps, giving access to the event information
+ * and aggregate data since the instantiation of this class.
+ *
+ * @hide
+ */
+public class ContextHubEventLogger {
+ private static final String TAG = "ContextHubEventLogger";
+
+ ContextHubEventLogger() {
+ throw new RuntimeException("Not implemented");
+ }
+
+ /**
+ * Logs a nanoapp load event
+ *
+ * @param contextHubId the ID of the context hub
+ * @param nanoAppId the ID of the nanoapp
+ * @param nanoAppVersion the version of the nanoapp
+ * @param nanoAppSize the size in bytes of the nanoapp
+ * @param success whether the load was successful
+ */
+ public void logNanoAppLoad(int contextHubId, long nanoAppId, int nanoAppVersion,
+ long nanoAppSize, boolean success) {
+ throw new RuntimeException("Not implemented");
+ }
+
+ /**
+ * Logs a nanoapp unload event
+ *
+ * @param contextHubId the ID of the context hub
+ * @param nanoAppId the ID of the nanoapp
+ * @param success whether the unload was successful
+ */
+ public void logNanoAppUnload(int contextHubId, long nanoAppId, boolean success) {
+ throw new RuntimeException("Not implemented");
+ }
+
+ /**
+ * Logs the event where a nanoapp sends a message to a client
+ *
+ * @param contextHubId the ID of the context hub
+ * @param message the message that was sent
+ */
+ public void logMessageFromNanoApp(int contextHubId, NanoAppMessage message) {
+ throw new RuntimeException("Not implemented");
+ }
+
+ /**
+ * Logs the event where a client sends a message to a nanoapp
+ *
+ * @param contextHubId the ID of the context hub
+ * @param message the message that was sent
+ * @param success whether the message was sent successfully
+ */
+ public void logMessageToNanoApp(int contextHubId, NanoAppMessage message, boolean success) {
+ throw new RuntimeException("Not implemented");
+ }
+
+ /**
+ * Logs a context hub restart event
+ *
+ * @param contextHubId the ID of the context hub
+ */
+ public void logContextHubRestarts(int contextHubId) {
+ throw new RuntimeException("Not implemented");
+ }
+
+ /**
+ * Creates a string representation of the logged events
+ *
+ * @return the dumped events
+ */
+ public String dump() {
+ throw new RuntimeException("Not implemented");
+ }
+
+ @Override
+ public String toString() {
+ return dump();
+ }
+}
diff --git a/services/core/java/com/android/server/notification/PreferencesHelper.java b/services/core/java/com/android/server/notification/PreferencesHelper.java
index 729c521a4ce0..477b8da61e0f 100644
--- a/services/core/java/com/android/server/notification/PreferencesHelper.java
+++ b/services/core/java/com/android/server/notification/PreferencesHelper.java
@@ -86,7 +86,6 @@ import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -1328,17 +1327,16 @@ public class PreferencesHelper implements RankingConfig {
return null;
}
NotificationChannelGroup group = r.groups.get(groupId).clone();
- ArrayList channels = new ArrayList();
+ group.setChannels(new ArrayList<>());
int N = r.channels.size();
for (int i = 0; i < N; i++) {
final NotificationChannel nc = r.channels.valueAt(i);
if (includeDeleted || !nc.isDeleted()) {
if (groupId.equals(nc.getGroup())) {
- channels.add(nc);
+ group.addChannel(nc);
}
}
}
- group.setChannels(channels);
return group;
}
}
@@ -1351,10 +1349,7 @@ public class PreferencesHelper implements RankingConfig {
if (r == null) {
return null;
}
- if (r.groups.get(groupId) != null) {
- return r.groups.get(groupId).clone();
- }
- return null;
+ return r.groups.get(groupId);
}
}
@@ -1362,48 +1357,44 @@ public class PreferencesHelper implements RankingConfig {
public ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
int uid, boolean includeDeleted, boolean includeNonGrouped, boolean includeEmpty) {
Objects.requireNonNull(pkg);
- List<NotificationChannelGroup> groups = new ArrayList<>();
+ Map<String, NotificationChannelGroup> groups = new ArrayMap<>();
synchronized (mPackagePreferences) {
PackagePreferences r = getPackagePreferencesLocked(pkg, uid);
if (r == null) {
return ParceledListSlice.emptyList();
}
- Map<String, ArrayList<NotificationChannel>> groupedChannels = new HashMap();
+ NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null);
int N = r.channels.size();
for (int i = 0; i < N; i++) {
final NotificationChannel nc = r.channels.valueAt(i);
if (includeDeleted || !nc.isDeleted()) {
if (nc.getGroup() != null) {
if (r.groups.get(nc.getGroup()) != null) {
- ArrayList<NotificationChannel> channels = groupedChannels.getOrDefault(
- nc.getGroup(), new ArrayList<>());
- channels.add(nc);
- groupedChannels.put(nc.getGroup(), channels);
+ NotificationChannelGroup ncg = groups.get(nc.getGroup());
+ if (ncg == null) {
+ ncg = r.groups.get(nc.getGroup()).clone();
+ ncg.setChannels(new ArrayList<>());
+ groups.put(nc.getGroup(), ncg);
+
+ }
+ ncg.addChannel(nc);
}
} else {
- ArrayList<NotificationChannel> channels = groupedChannels.getOrDefault(
- null, new ArrayList<>());
- channels.add(nc);
- groupedChannels.put(null, channels);
+ nonGrouped.addChannel(nc);
}
}
}
- for (NotificationChannelGroup group : r.groups.values()) {
- ArrayList<NotificationChannel> channels =
- groupedChannels.getOrDefault(group.getId(), new ArrayList<>());
- if (includeEmpty || !channels.isEmpty()) {
- NotificationChannelGroup clone = group.clone();
- clone.setChannels(channels);
- groups.add(clone);
- }
+ if (includeNonGrouped && nonGrouped.getChannels().size() > 0) {
+ groups.put(null, nonGrouped);
}
-
- if (includeNonGrouped && groupedChannels.containsKey(null)) {
- NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null);
- nonGrouped.setChannels(groupedChannels.get(null));
- groups.add(nonGrouped);
+ if (includeEmpty) {
+ for (NotificationChannelGroup group : r.groups.values()) {
+ if (!groups.containsKey(group.getId())) {
+ groups.put(group.getId(), group);
+ }
+ }
}
- return new ParceledListSlice<>(groups);
+ return new ParceledListSlice<>(new ArrayList<>(groups.values()));
}
}
diff --git a/services/core/java/com/android/server/om/OverlayManagerShellCommand.java b/services/core/java/com/android/server/om/OverlayManagerShellCommand.java
index da76738fa025..bb918d594167 100644
--- a/services/core/java/com/android/server/om/OverlayManagerShellCommand.java
+++ b/services/core/java/com/android/server/om/OverlayManagerShellCommand.java
@@ -257,6 +257,7 @@ final class OverlayManagerShellCommand extends ShellCommand {
String name = "";
String filename = null;
String opt;
+ String configuration = null;
while ((opt = getNextOption()) != null) {
switch (opt) {
case "--user":
@@ -274,6 +275,9 @@ final class OverlayManagerShellCommand extends ShellCommand {
case "--file":
filename = getNextArgRequired();
break;
+ case "--config":
+ configuration = getNextArgRequired();
+ break;
default:
err.println("Error: Unknown option: " + opt);
return 1;
@@ -307,7 +311,7 @@ final class OverlayManagerShellCommand extends ShellCommand {
final String resourceName = getNextArgRequired();
final String typeStr = getNextArgRequired();
final String strData = String.join(" ", peekRemainingArgs());
- addOverlayValue(overlayBuilder, resourceName, typeStr, strData);
+ addOverlayValue(overlayBuilder, resourceName, typeStr, strData, configuration);
}
mInterface.commit(new OverlayManagerTransaction.Builder()
@@ -363,8 +367,9 @@ final class OverlayManagerShellCommand extends ShellCommand {
err.println("Error: value missing at line " + parser.getLineNumber());
return 1;
}
+ String config = parser.getAttributeValue(null, "config");
addOverlayValue(overlayBuilder, targetPackage + ':' + target,
- overlayType, value);
+ overlayType, value, config);
}
}
}
@@ -379,7 +384,7 @@ final class OverlayManagerShellCommand extends ShellCommand {
}
private void addOverlayValue(FabricatedOverlay.Builder overlayBuilder,
- String resourceName, String typeString, String valueString) {
+ String resourceName, String typeString, String valueString, String configuration) {
final int type;
typeString = typeString.toLowerCase(Locale.getDefault());
if (TYPE_MAP.containsKey(typeString)) {
@@ -392,7 +397,7 @@ final class OverlayManagerShellCommand extends ShellCommand {
}
}
if (type == TypedValue.TYPE_STRING) {
- overlayBuilder.setResourceValue(resourceName, type, valueString);
+ overlayBuilder.setResourceValue(resourceName, type, valueString, configuration);
} else {
final int intData;
if (valueString.startsWith("0x")) {
@@ -400,7 +405,7 @@ final class OverlayManagerShellCommand extends ShellCommand {
} else {
intData = Integer.parseUnsignedInt(valueString);
}
- overlayBuilder.setResourceValue(resourceName, type, intData);
+ overlayBuilder.setResourceValue(resourceName, type, intData, configuration);
}
}
diff --git a/services/core/java/com/android/server/os/NativeTombstoneManager.java b/services/core/java/com/android/server/os/NativeTombstoneManager.java
index 45192b7bcdbe..d3d1cc5d05cb 100644
--- a/services/core/java/com/android/server/os/NativeTombstoneManager.java
+++ b/services/core/java/com/android/server/os/NativeTombstoneManager.java
@@ -109,6 +109,13 @@ public final class NativeTombstoneManager {
private void handleTombstone(File path) {
final String filename = path.getName();
+
+ // Clean up temporary files if they made it this far (e.g. if system server crashes).
+ if (filename.endsWith(".tmp")) {
+ path.delete();
+ return;
+ }
+
if (!filename.startsWith("tombstone_")) {
return;
}
@@ -561,6 +568,10 @@ public final class NativeTombstoneManager {
@Override
public void onEvent(int event, @Nullable String path) {
mHandler.post(() -> {
+ // Ignore .tmp files.
+ if (path.endsWith(".tmp")) {
+ return;
+ }
handleTombstone(new File(TOMBSTONE_DIR, path));
});
}
diff --git a/services/core/java/com/android/server/pm/InstallPackageHelper.java b/services/core/java/com/android/server/pm/InstallPackageHelper.java
index 9db9837ffc45..61e2419e2d14 100644
--- a/services/core/java/com/android/server/pm/InstallPackageHelper.java
+++ b/services/core/java/com/android/server/pm/InstallPackageHelper.java
@@ -899,7 +899,7 @@ final class InstallPackageHelper {
Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "reconcilePackages");
reconciledPackages = ReconcilePackageUtils.reconcilePackages(
reconcileRequest, mSharedLibraries,
- mPm.mSettings.getKeySetManagerService(), mPm.mSettings);
+ mPm.mSettings.getKeySetManagerService(), mPm.mSettings, mContext);
} catch (ReconcileFailure e) {
for (InstallRequest request : requests) {
request.mInstallResult.setError("Reconciliation failed...", e);
@@ -3669,7 +3669,7 @@ final class InstallPackageHelper {
final Map<String, ReconciledPackage> reconcileResult =
ReconcilePackageUtils.reconcilePackages(reconcileRequest,
mSharedLibraries, mPm.mSettings.getKeySetManagerService(),
- mPm.mSettings);
+ mPm.mSettings, mContext);
if ((scanFlags & SCAN_AS_APEX) == 0) {
appIdCreated = optimisticallyRegisterAppId(scanResult);
} else {
diff --git a/services/core/java/com/android/server/pm/ReconcilePackageUtils.java b/services/core/java/com/android/server/pm/ReconcilePackageUtils.java
index d6a133e43789..3c4780171ee5 100644
--- a/services/core/java/com/android/server/pm/ReconcilePackageUtils.java
+++ b/services/core/java/com/android/server/pm/ReconcilePackageUtils.java
@@ -16,6 +16,7 @@
package com.android.server.pm;
+import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
import static android.content.pm.SigningDetails.CapabilityMergeRule.MERGE_RESTRICTED_CAPABILITY;
@@ -23,25 +24,31 @@ import static android.content.pm.SigningDetails.CapabilityMergeRule.MERGE_RESTRI
import static com.android.server.pm.PackageManagerService.SCAN_BOOTING;
import static com.android.server.pm.PackageManagerService.SCAN_DONT_KILL_APP;
+import android.content.Context;
import android.content.pm.PackageManager;
+import android.content.pm.PermissionInfo;
import android.content.pm.SharedLibraryInfo;
import android.content.pm.SigningDetails;
import android.os.SystemProperties;
+import android.permission.PermissionManager;
import android.util.ArrayMap;
import android.util.Log;
import com.android.server.pm.parsing.pkg.AndroidPackage;
import com.android.server.pm.parsing.pkg.ParsedPackage;
+import com.android.server.pm.pkg.component.ParsedUsesPermission;
import com.android.server.pm.pkg.parsing.ParsingPackageUtils;
import com.android.server.utils.WatchedLongSparseArray;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
final class ReconcilePackageUtils {
public static Map<String, ReconciledPackage> reconcilePackages(
final ReconcileRequest request, SharedLibrariesImpl sharedLibraries,
- KeySetManagerService ksms, Settings settings)
+ KeySetManagerService ksms, Settings settings, Context context)
throws ReconcileFailure {
final Map<String, ScanResult> scannedPackages = request.mScannedPackages;
@@ -161,11 +168,43 @@ final class ReconcilePackageUtils {
// over the latest parsed certs.
signingDetails = parsedPackage.getSigningDetails();
- // if this is is a sharedUser, check to see if the new package is signed by a
- // newer
- // signing certificate than the existing one, and if so, copy over the new
+ // if this is a sharedUser, check to see if the new package is signed by a
+ // newer signing certificate than the existing one, and if so, copy over the new
// details
if (sharedUserSetting != null) {
+ if (prepareResult != null && !prepareResult.mPackageToScan.isTestOnly()
+ && sharedUserSetting.isPrivileged()
+ && !signatureCheckPs.isSystem()) {
+ final List<ParsedUsesPermission> usesPermissions =
+ parsedPackage.getUsesPermissions();
+ final List<String> usesPrivilegedPermissions = new ArrayList<>();
+ final PermissionManager permissionManager = context.getSystemService(
+ PermissionManager.class);
+ // Check if the app requests any privileged permissions because that
+ // violates the privapp-permissions allowlist check during boot.
+ if (permissionManager != null) {
+ for (int i = 0; i < usesPermissions.size(); i++) {
+ final String permissionName = usesPermissions.get(i).getName();
+ final PermissionInfo permissionInfo =
+ permissionManager.getPermissionInfo(permissionName, 0);
+ if (permissionInfo != null
+ && (permissionInfo.getProtectionFlags()
+ & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
+ usesPrivilegedPermissions.add(permissionName);
+ }
+ }
+ }
+
+ if (!usesPrivilegedPermissions.isEmpty()) {
+ throw new ReconcileFailure(INSTALL_FAILED_INVALID_APK,
+ "Non-system package: " + parsedPackage.getPackageName()
+ + " shares signature and sharedUserId with"
+ + " a privileged package but requests"
+ + " privileged permissions that are not"
+ + " allowed: " + Arrays.toString(
+ usesPrivilegedPermissions.toArray()));
+ }
+ }
// Attempt to merge the existing lineage for the shared SigningDetails with
// the lineage of the new package; if the shared SigningDetails are not
// returned this indicates the new package added new signers to the lineage
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index e423ea9170d7..672c13c2dbf9 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -911,7 +911,7 @@ public class UserManagerService extends IUserManager.Stub {
private @NonNull List<UserInfo> getUsersInternal(boolean excludePartial, boolean excludeDying,
boolean excludePreCreated) {
synchronized (mUsersLock) {
- ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
+ ArrayList<UserInfo> users = new ArrayList<>(mUsers.size());
final int userSize = mUsers.size();
for (int i = 0; i < userSize; i++) {
UserInfo ui = mUsers.valueAt(i).info;
@@ -1767,6 +1767,32 @@ public class UserManagerService extends IUserManager.Stub {
}
@Override
+ public List<UserHandle> getVisibleUsers() {
+ if (!hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) {
+ throw new SecurityException("Caller needs MANAGE_USERS or INTERACT_ACROSS_USERS "
+ + "permission to get list of visible users");
+ }
+ final long ident = Binder.clearCallingIdentity();
+ try {
+ // TODO(b/2399825580): refactor into UserDisplayAssigner
+ synchronized (mUsersLock) {
+ int usersSize = mUsers.size();
+ ArrayList<UserHandle> visibleUsers = new ArrayList<>(usersSize);
+ for (int i = 0; i < usersSize; i++) {
+ UserInfo ui = mUsers.valueAt(i).info;
+ if (!ui.partial && !ui.preCreated && !mRemovingUserIds.get(ui.id)
+ && isUserVisibleUnchecked(ui.id)) {
+ visibleUsers.add(UserHandle.of(ui.id));
+ }
+ }
+ return visibleUsers;
+ }
+ } finally {
+ Binder.restoreCallingIdentity(ident);
+ }
+ }
+
+ @Override
public @NonNull String getUserName() {
final int callingUid = Binder.getCallingUid();
if (!hasQueryOrCreateUsersPermission()
diff --git a/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java b/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java
index 9ad15c8b538d..f00edf3a76c5 100644
--- a/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java
+++ b/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java
@@ -49,7 +49,7 @@ public final class SingleKeyGestureDetector {
// Key code of current key down event, reset when key up.
private int mDownKeyCode = KeyEvent.KEYCODE_UNKNOWN;
- private volatile boolean mHandledByLongPress = false;
+ private boolean mHandledByLongPress = false;
private final Handler mHandler;
private long mLastDownTime = 0;
@@ -194,8 +194,8 @@ public final class SingleKeyGestureDetector {
mHandledByLongPress = true;
mHandler.removeMessages(MSG_KEY_LONG_PRESS);
mHandler.removeMessages(MSG_KEY_VERY_LONG_PRESS);
- final Message msg = mHandler.obtainMessage(MSG_KEY_LONG_PRESS, mActiveRule.mKeyCode,
- 0, mActiveRule);
+ final Message msg = mHandler.obtainMessage(MSG_KEY_LONG_PRESS, keyCode, 0,
+ mActiveRule);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
@@ -274,13 +274,26 @@ public final class SingleKeyGestureDetector {
}
private boolean interceptKeyUp(KeyEvent event) {
- mHandler.removeMessages(MSG_KEY_LONG_PRESS);
- mHandler.removeMessages(MSG_KEY_VERY_LONG_PRESS);
mDownKeyCode = KeyEvent.KEYCODE_UNKNOWN;
if (mActiveRule == null) {
return false;
}
+ if (!mHandledByLongPress) {
+ final long eventTime = event.getEventTime();
+ if (eventTime < mLastDownTime + mActiveRule.getLongPressTimeoutMs()) {
+ mHandler.removeMessages(MSG_KEY_LONG_PRESS);
+ } else {
+ mHandledByLongPress = mActiveRule.supportLongPress();
+ }
+
+ if (eventTime < mLastDownTime + mActiveRule.getVeryLongPressTimeoutMs()) {
+ mHandler.removeMessages(MSG_KEY_VERY_LONG_PRESS);
+ } else {
+ mHandledByLongPress = mActiveRule.supportVeryLongPress();
+ }
+ }
+
if (mHandledByLongPress) {
mHandledByLongPress = false;
mKeyPressCounter = 0;
@@ -376,7 +389,6 @@ public final class SingleKeyGestureDetector {
if (DEBUG) {
Log.i(TAG, "Detect long press " + KeyEvent.keyCodeToString(keyCode));
}
- mHandledByLongPress = true;
rule.onLongPress(mLastDownTime);
break;
case MSG_KEY_VERY_LONG_PRESS:
@@ -384,7 +396,6 @@ public final class SingleKeyGestureDetector {
Log.i(TAG, "Detect very long press "
+ KeyEvent.keyCodeToString(keyCode));
}
- mHandledByLongPress = true;
rule.onVeryLongPress(mLastDownTime);
break;
case MSG_KEY_DELAYED_PRESS:
diff --git a/services/core/java/com/android/server/power/Notifier.java b/services/core/java/com/android/server/power/Notifier.java
index dad9584c6722..5a2fb18673ac 100644
--- a/services/core/java/com/android/server/power/Notifier.java
+++ b/services/core/java/com/android/server/power/Notifier.java
@@ -571,8 +571,7 @@ public class Notifier {
/**
* Called when there has been user activity.
*/
- public void onUserActivity(int displayGroupId, @PowerManager.UserActivityEvent int event,
- int uid) {
+ public void onUserActivity(int displayGroupId, int event, int uid) {
if (DEBUG) {
Slog.d(TAG, "onUserActivity: event=" + event + ", uid=" + uid);
}
diff --git a/services/core/java/com/android/server/power/PowerGroup.java b/services/core/java/com/android/server/power/PowerGroup.java
index 9fe53fbfaf25..fec61ac8f2cf 100644
--- a/services/core/java/com/android/server/power/PowerGroup.java
+++ b/services/core/java/com/android/server/power/PowerGroup.java
@@ -74,8 +74,6 @@ public class PowerGroup {
private long mLastPowerOnTime;
private long mLastUserActivityTime;
private long mLastUserActivityTimeNoChangeLights;
- @PowerManager.UserActivityEvent
- private int mLastUserActivityEvent;
/** Timestamp (milliseconds since boot) of the last time the power group was awoken.*/
private long mLastWakeTime;
/** Timestamp (milliseconds since boot) of the last time the power group was put to sleep. */
@@ -246,7 +244,7 @@ public class PowerGroup {
return true;
}
- boolean dozeLocked(long eventTime, int uid, @PowerManager.GoToSleepReason int reason) {
+ boolean dozeLocked(long eventTime, int uid, int reason) {
if (eventTime < getLastWakeTimeLocked() || !isInteractive(mWakefulness)) {
return false;
}
@@ -255,14 +253,9 @@ public class PowerGroup {
try {
reason = Math.min(PowerManager.GO_TO_SLEEP_REASON_MAX,
Math.max(reason, PowerManager.GO_TO_SLEEP_REASON_MIN));
- long millisSinceLastUserActivity = eventTime - Math.max(
- mLastUserActivityTimeNoChangeLights, mLastUserActivityTime);
Slog.i(TAG, "Powering off display group due to "
- + PowerManager.sleepReasonToString(reason)
- + " (groupId= " + getGroupId() + ", uid= " + uid
- + ", millisSinceLastUserActivity=" + millisSinceLastUserActivity
- + ", lastUserActivityEvent=" + PowerManager.userActivityEventToString(
- mLastUserActivityEvent) + ")...");
+ + PowerManager.sleepReasonToString(reason) + " (groupId= " + getGroupId()
+ + ", uid= " + uid + ")...");
setSandmanSummonedLocked(/* isSandmanSummoned= */ true);
setWakefulnessLocked(WAKEFULNESS_DOZING, eventTime, uid, reason, /* opUid= */ 0,
@@ -273,16 +266,14 @@ public class PowerGroup {
return true;
}
- boolean sleepLocked(long eventTime, int uid, @PowerManager.GoToSleepReason int reason) {
+ boolean sleepLocked(long eventTime, int uid, int reason) {
if (eventTime < mLastWakeTime || getWakefulnessLocked() == WAKEFULNESS_ASLEEP) {
return false;
}
Trace.traceBegin(Trace.TRACE_TAG_POWER, "sleepPowerGroup");
try {
- Slog.i(TAG,
- "Sleeping power group (groupId=" + getGroupId() + ", uid=" + uid + ", reason="
- + PowerManager.sleepReasonToString(reason) + ")...");
+ Slog.i(TAG, "Sleeping power group (groupId=" + getGroupId() + ", uid=" + uid + ")...");
setSandmanSummonedLocked(/* isSandmanSummoned= */ true);
setWakefulnessLocked(WAKEFULNESS_ASLEEP, eventTime, uid, reason, /* opUid= */0,
/* opPackageName= */ null, /* details= */ null);
@@ -296,20 +287,16 @@ public class PowerGroup {
return mLastUserActivityTime;
}
- void setLastUserActivityTimeLocked(long lastUserActivityTime,
- @PowerManager.UserActivityEvent int event) {
+ void setLastUserActivityTimeLocked(long lastUserActivityTime) {
mLastUserActivityTime = lastUserActivityTime;
- mLastUserActivityEvent = event;
}
public long getLastUserActivityTimeNoChangeLightsLocked() {
return mLastUserActivityTimeNoChangeLights;
}
- public void setLastUserActivityTimeNoChangeLightsLocked(long time,
- @PowerManager.UserActivityEvent int event) {
+ public void setLastUserActivityTimeNoChangeLightsLocked(long time) {
mLastUserActivityTimeNoChangeLights = time;
- mLastUserActivityEvent = event;
}
public int getUserActivitySummaryLocked() {
diff --git a/services/core/java/com/android/server/power/PowerManagerService.java b/services/core/java/com/android/server/power/PowerManagerService.java
index ca3599ca7fa0..2a1748c441dc 100644
--- a/services/core/java/com/android/server/power/PowerManagerService.java
+++ b/services/core/java/com/android/server/power/PowerManagerService.java
@@ -1216,7 +1216,6 @@ public final class PowerManagerService extends SystemService
return;
}
- Slog.i(TAG, "onFlip(): Face " + (isFaceDown ? "down." : "up."));
mIsFaceDown = isFaceDown;
if (isFaceDown) {
final long currentTime = mClock.uptimeMillis();
@@ -1938,13 +1937,12 @@ public final class PowerManagerService extends SystemService
// Called from native code.
@SuppressWarnings("unused")
- private void userActivityFromNative(long eventTime, @PowerManager.UserActivityEvent int event,
- int displayId, int flags) {
+ private void userActivityFromNative(long eventTime, int event, int displayId, int flags) {
userActivityInternal(displayId, eventTime, event, flags, Process.SYSTEM_UID);
}
- private void userActivityInternal(int displayId, long eventTime,
- @PowerManager.UserActivityEvent int event, int flags, int uid) {
+ private void userActivityInternal(int displayId, long eventTime, int event, int flags,
+ int uid) {
synchronized (mLock) {
if (displayId == Display.INVALID_DISPLAY) {
if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
@@ -1995,12 +1993,11 @@ public final class PowerManagerService extends SystemService
@GuardedBy("mLock")
private boolean userActivityNoUpdateLocked(final PowerGroup powerGroup, long eventTime,
- @PowerManager.UserActivityEvent int event, int flags, int uid) {
+ int event, int flags, int uid) {
final int groupId = powerGroup.getGroupId();
if (DEBUG_SPEW) {
Slog.d(TAG, "userActivityNoUpdateLocked: groupId=" + groupId
- + ", eventTime=" + eventTime
- + ", event=" + PowerManager.userActivityEventToString(event)
+ + ", eventTime=" + eventTime + ", event=" + event
+ ", flags=0x" + Integer.toHexString(flags) + ", uid=" + uid);
}
@@ -2035,7 +2032,7 @@ public final class PowerManagerService extends SystemService
if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
if (eventTime > powerGroup.getLastUserActivityTimeNoChangeLightsLocked()
&& eventTime > powerGroup.getLastUserActivityTimeLocked()) {
- powerGroup.setLastUserActivityTimeNoChangeLightsLocked(eventTime, event);
+ powerGroup.setLastUserActivityTimeNoChangeLightsLocked(eventTime);
mDirty |= DIRTY_USER_ACTIVITY;
if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
mDirty |= DIRTY_QUIESCENT;
@@ -2045,7 +2042,7 @@ public final class PowerManagerService extends SystemService
}
} else {
if (eventTime > powerGroup.getLastUserActivityTimeLocked()) {
- powerGroup.setLastUserActivityTimeLocked(eventTime, event);
+ powerGroup.setLastUserActivityTimeLocked(eventTime);
mDirty |= DIRTY_USER_ACTIVITY;
if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
mDirty |= DIRTY_QUIESCENT;
@@ -2072,8 +2069,7 @@ public final class PowerManagerService extends SystemService
@WakeReason int reason, String details, int uid, String opPackageName, int opUid) {
if (DEBUG_SPEW) {
Slog.d(TAG, "wakePowerGroupLocked: eventTime=" + eventTime
- + ", groupId=" + powerGroup.getGroupId()
- + ", reason=" + PowerManager.wakeReasonToString(reason) + ", uid=" + uid);
+ + ", groupId=" + powerGroup.getGroupId() + ", uid=" + uid);
}
if (mForceSuspendActive || !mSystemReady) {
return;
@@ -2096,11 +2092,11 @@ public final class PowerManagerService extends SystemService
@GuardedBy("mLock")
private boolean dozePowerGroupLocked(final PowerGroup powerGroup, long eventTime,
- @GoToSleepReason int reason, int uid) {
+ int reason, int uid) {
if (DEBUG_SPEW) {
Slog.d(TAG, "dozePowerGroup: eventTime=" + eventTime
- + ", groupId=" + powerGroup.getGroupId()
- + ", reason=" + PowerManager.sleepReasonToString(reason) + ", uid=" + uid);
+ + ", groupId=" + powerGroup.getGroupId() + ", reason=" + reason
+ + ", uid=" + uid);
}
if (!mSystemReady || !mBootCompleted) {
@@ -2111,12 +2107,10 @@ public final class PowerManagerService extends SystemService
}
@GuardedBy("mLock")
- private boolean sleepPowerGroupLocked(final PowerGroup powerGroup, long eventTime,
- @GoToSleepReason int reason, int uid) {
+ private boolean sleepPowerGroupLocked(final PowerGroup powerGroup, long eventTime, int reason,
+ int uid) {
if (DEBUG_SPEW) {
- Slog.d(TAG, "sleepPowerGroup: eventTime=" + eventTime
- + ", groupId=" + powerGroup.getGroupId()
- + ", reason=" + PowerManager.sleepReasonToString(reason) + ", uid=" + uid);
+ Slog.d(TAG, "sleepPowerGroup: eventTime=" + eventTime + ", uid=" + uid);
}
if (!mBootCompleted || !mSystemReady) {
return false;
@@ -2178,11 +2172,7 @@ public final class PowerManagerService extends SystemService
case WAKEFULNESS_DOZING:
traceMethodName = "goToSleep";
Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason)
- + " (uid " + uid + ", screenOffTimeout=" + mScreenOffTimeoutSetting
- + ", activityTimeoutWM=" + mUserActivityTimeoutOverrideFromWindowManager
- + ", maxDimRatio=" + mMaximumScreenDimRatioConfig
- + ", maxDimDur=" + mMaximumScreenDimDurationConfig + ")...");
-
+ + " (uid " + uid + ")...");
mLastGlobalSleepTime = eventTime;
mLastGlobalSleepReason = reason;
mLastGlobalSleepTimeRealtime = mClock.elapsedRealtime();
@@ -4267,7 +4257,7 @@ public final class PowerManagerService extends SystemService
void onUserActivity() {
synchronized (mLock) {
mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP).setLastUserActivityTimeLocked(
- mClock.uptimeMillis(), PowerManager.USER_ACTIVITY_EVENT_OTHER);
+ mClock.uptimeMillis());
}
}
@@ -5655,8 +5645,7 @@ public final class PowerManagerService extends SystemService
}
@Override // Binder call
- public void userActivity(int displayId, long eventTime,
- @PowerManager.UserActivityEvent int event, int flags) {
+ public void userActivity(int displayId, long eventTime, int event, int flags) {
final long now = mClock.uptimeMillis();
if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
!= PackageManager.PERMISSION_GRANTED
diff --git a/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java b/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java
index 202beb377b2c..0c9ada8fa6db 100644
--- a/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java
+++ b/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java
@@ -5911,8 +5911,7 @@ public class BatteryStatsImpl extends BatteryStats {
}
@GuardedBy("this")
- public void noteUserActivityLocked(int uid, @PowerManager.UserActivityEvent int event,
- long elapsedRealtimeMs, long uptimeMs) {
+ public void noteUserActivityLocked(int uid, int event, long elapsedRealtimeMs, long uptimeMs) {
if (mOnBatteryInternal) {
uid = mapUid(uid);
getUidStatsLocked(uid, elapsedRealtimeMs, uptimeMs).noteUserActivityLocked(event);
@@ -9417,14 +9416,14 @@ public class BatteryStatsImpl extends BatteryStats {
}
@Override
- public void noteUserActivityLocked(@PowerManager.UserActivityEvent int event) {
+ public void noteUserActivityLocked(int type) {
if (mUserActivityCounters == null) {
initUserActivityLocked();
}
- if (event >= 0 && event < NUM_USER_ACTIVITY_TYPES) {
- mUserActivityCounters[event].stepAtomic();
+ if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
+ mUserActivityCounters[type].stepAtomic();
} else {
- Slog.w(TAG, "Unknown user activity event " + event + " was specified.",
+ Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
new Throwable());
}
}
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index 4153ea5cb936..c04b19558770 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -1655,8 +1655,7 @@ final class AccessibilityController {
}
// If the window is completely covered by other windows - ignore.
- Region intersectionWindow = mTempRegion1;
- if (!intersectionWindow.op(unaccountedSpace, regionInScreen, Region.Op.INTERSECT)) {
+ if (unaccountedSpace.quickReject(regionInScreen)) {
return false;
}
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index 765e7f08d201..f8f94f655a16 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -312,7 +312,6 @@ import android.util.TypedXmlPullParser;
import android.util.TypedXmlSerializer;
import android.util.proto.ProtoOutputStream;
import android.view.AppTransitionAnimationSpec;
-import android.view.DisplayCutout;
import android.view.DisplayInfo;
import android.view.IAppTransitionAnimationSpecsFuture;
import android.view.InputApplicationHandle;
@@ -357,6 +356,7 @@ import com.android.server.wm.ActivityMetricsLogger.TransitionInfoSnapshot;
import com.android.server.wm.SurfaceAnimator.AnimationType;
import com.android.server.wm.WindowManagerService.H;
import com.android.server.wm.utils.InsetUtils;
+import com.android.server.wm.utils.WmDisplayCutout;
import dalvik.annotation.optimization.NeverCompile;
@@ -9684,9 +9684,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A
final boolean rotated = (rotation == ROTATION_90 || rotation == ROTATION_270);
final int dw = rotated ? display.mBaseDisplayHeight : display.mBaseDisplayWidth;
final int dh = rotated ? display.mBaseDisplayWidth : display.mBaseDisplayHeight;
- final DisplayCutout cutout = display.calculateDisplayCutoutForRotation(rotation)
- .getDisplayCutout();
- policy.getNonDecorInsetsLw(rotation, cutout, mNonDecorInsets[rotation]);
+ final WmDisplayCutout cutout = display.calculateDisplayCutoutForRotation(rotation);
+ policy.getNonDecorInsetsLw(rotation, dw, dh, cutout, mNonDecorInsets[rotation]);
mStableInsets[rotation].set(mNonDecorInsets[rotation]);
policy.convertNonDecorInsetsToStableInsets(mStableInsets[rotation], rotation);
diff --git a/services/core/java/com/android/server/wm/BLASTSyncEngine.java b/services/core/java/com/android/server/wm/BLASTSyncEngine.java
index 9a94a4f54b61..d3452277a29f 100644
--- a/services/core/java/com/android/server/wm/BLASTSyncEngine.java
+++ b/services/core/java/com/android/server/wm/BLASTSyncEngine.java
@@ -22,6 +22,7 @@ import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_SYNC_ENGINE;
import static com.android.server.wm.WindowState.BLAST_TIMEOUT_DURATION;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.os.Trace;
import android.util.ArraySet;
import android.util.Slog;
@@ -63,6 +64,15 @@ import java.util.ArrayList;
class BLASTSyncEngine {
private static final String TAG = "BLASTSyncEngine";
+ /** No specific method. Used by override specifiers. */
+ public static final int METHOD_UNDEFINED = -1;
+
+ /** No sync method. Apps will draw/present internally and just report. */
+ public static final int METHOD_NONE = 0;
+
+ /** Sync with BLAST. Apps will draw and then send the buffer to be applied in sync. */
+ public static final int METHOD_BLAST = 1;
+
interface TransactionReadyListener {
void onTransactionReady(int mSyncId, SurfaceControl.Transaction transaction);
}
@@ -85,6 +95,7 @@ class BLASTSyncEngine {
*/
class SyncGroup {
final int mSyncId;
+ final int mSyncMethod;
final TransactionReadyListener mListener;
final Runnable mOnTimeout;
boolean mReady = false;
@@ -92,8 +103,9 @@ class BLASTSyncEngine {
private SurfaceControl.Transaction mOrphanTransaction = null;
private String mTraceName;
- private SyncGroup(TransactionReadyListener listener, int id, String name) {
+ private SyncGroup(TransactionReadyListener listener, int id, String name, int method) {
mSyncId = id;
+ mSyncMethod = method;
mListener = listener;
mOnTimeout = () -> {
Slog.w(TAG, "Sync group " + mSyncId + " timeout");
@@ -271,16 +283,13 @@ class BLASTSyncEngine {
* Prepares a {@link SyncGroup} that is not active yet. Caller must call {@link #startSyncSet}
* before calling {@link #addToSyncSet(int, WindowContainer)} on any {@link WindowContainer}.
*/
- SyncGroup prepareSyncSet(TransactionReadyListener listener, String name) {
- return new SyncGroup(listener, mNextSyncId++, name);
+ SyncGroup prepareSyncSet(TransactionReadyListener listener, String name, int method) {
+ return new SyncGroup(listener, mNextSyncId++, name, method);
}
- int startSyncSet(TransactionReadyListener listener) {
- return startSyncSet(listener, BLAST_TIMEOUT_DURATION, "");
- }
-
- int startSyncSet(TransactionReadyListener listener, long timeoutMs, String name) {
- final SyncGroup s = prepareSyncSet(listener, name);
+ int startSyncSet(TransactionReadyListener listener, long timeoutMs, String name,
+ int method) {
+ final SyncGroup s = prepareSyncSet(listener, name, method);
startSyncSet(s, timeoutMs);
return s.mSyncId;
}
@@ -302,6 +311,11 @@ class BLASTSyncEngine {
scheduleTimeout(s, timeoutMs);
}
+ @Nullable
+ SyncGroup getSyncSet(int id) {
+ return mActiveSyncs.get(id);
+ }
+
boolean hasActiveSync() {
return mActiveSyncs.size() != 0;
}
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 8a34af3b0107..77737028fd37 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -441,7 +441,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
*/
final DisplayMetrics mRealDisplayMetrics = new DisplayMetrics();
- /** @see #computeCompatSmallestWidth(boolean, int, int, int) */
+ /** @see #computeCompatSmallestWidth(boolean, int, int) */
private final DisplayMetrics mTmpDisplayMetrics = new DisplayMetrics();
/**
@@ -2017,7 +2017,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
// the top of the method, the caller is obligated to call computeNewConfigurationLocked().
// By updating the Display info here it will be available to
// #computeScreenConfiguration() later.
- updateDisplayAndOrientation(getConfiguration().uiMode, null /* outConfig */);
+ updateDisplayAndOrientation(null /* outConfig */);
// NOTE: We disable the rotation in the emulator because
// it doesn't support hardware OpenGL emulation yet.
@@ -2067,7 +2067,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
* changed.
* Do not call if {@link WindowManagerService#mDisplayReady} == false.
*/
- private DisplayInfo updateDisplayAndOrientation(int uiMode, Configuration outConfig) {
+ private DisplayInfo updateDisplayAndOrientation(Configuration outConfig) {
// Use the effective "visual" dimensions based on current rotation
final int rotation = getRotation();
final boolean rotated = (rotation == ROTATION_90 || rotation == ROTATION_270);
@@ -2079,18 +2079,16 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
final DisplayCutout displayCutout = wmDisplayCutout.getDisplayCutout();
final RoundedCorners roundedCorners = calculateRoundedCornersForRotation(rotation);
- final int appWidth = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode,
- displayCutout);
- final int appHeight = mDisplayPolicy.getNonDecorDisplayHeight(dh, rotation,
- displayCutout);
+ final Rect appFrame = mDisplayPolicy.getNonDecorDisplayFrame(dw, dh, rotation,
+ wmDisplayCutout);
mDisplayInfo.rotation = rotation;
mDisplayInfo.logicalWidth = dw;
mDisplayInfo.logicalHeight = dh;
mDisplayInfo.logicalDensityDpi = mBaseDisplayDensity;
mDisplayInfo.physicalXDpi = mBaseDisplayPhysicalXDpi;
mDisplayInfo.physicalYDpi = mBaseDisplayPhysicalYDpi;
- mDisplayInfo.appWidth = appWidth;
- mDisplayInfo.appHeight = appHeight;
+ mDisplayInfo.appWidth = appFrame.width();
+ mDisplayInfo.appHeight = appFrame.height();
if (isDefaultDisplay) {
mDisplayInfo.getLogicalMetrics(mRealDisplayMetrics,
CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, null);
@@ -2104,7 +2102,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
mDisplayInfo.flags &= ~Display.FLAG_SCALING_DISABLED;
}
- computeSizeRangesAndScreenLayout(mDisplayInfo, rotated, uiMode, dw, dh,
+ computeSizeRangesAndScreenLayout(mDisplayInfo, rotated, dw, dh,
mDisplayMetrics.density, outConfig);
mWmService.mDisplayManagerInternal.setDisplayInfoOverrideFromWindowManager(mDisplayId,
@@ -2194,10 +2192,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
outConfig.windowConfiguration.setMaxBounds(0, 0, dw, dh);
outConfig.windowConfiguration.setBounds(outConfig.windowConfiguration.getMaxBounds());
- final int uiMode = getConfiguration().uiMode;
- final DisplayCutout displayCutout =
- calculateDisplayCutoutForRotation(rotation).getDisplayCutout();
- computeScreenAppConfiguration(outConfig, dw, dh, rotation, uiMode, displayCutout);
+ final WmDisplayCutout wmDisplayCutout = calculateDisplayCutoutForRotation(rotation);
+ computeScreenAppConfiguration(outConfig, dw, dh, rotation, wmDisplayCutout);
final DisplayInfo displayInfo = new DisplayInfo(mDisplayInfo);
displayInfo.rotation = rotation;
@@ -2206,38 +2202,35 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
final Rect appBounds = outConfig.windowConfiguration.getAppBounds();
displayInfo.appWidth = appBounds.width();
displayInfo.appHeight = appBounds.height();
+ final DisplayCutout displayCutout = wmDisplayCutout.getDisplayCutout();
displayInfo.displayCutout = displayCutout.isEmpty() ? null : displayCutout;
- computeSizeRangesAndScreenLayout(displayInfo, rotated, uiMode, dw, dh,
+ computeSizeRangesAndScreenLayout(displayInfo, rotated, dw, dh,
mDisplayMetrics.density, outConfig);
return displayInfo;
}
/** Compute configuration related to application without changing current display. */
private void computeScreenAppConfiguration(Configuration outConfig, int dw, int dh,
- int rotation, int uiMode, DisplayCutout displayCutout) {
- final int appWidth = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode,
- displayCutout);
- final int appHeight = mDisplayPolicy.getNonDecorDisplayHeight(dh, rotation,
- displayCutout);
- mDisplayPolicy.getNonDecorInsetsLw(rotation, displayCutout, mTmpRect);
- final int leftInset = mTmpRect.left;
- final int topInset = mTmpRect.top;
+ int rotation, WmDisplayCutout wmDisplayCutout) {
+ final DisplayFrames displayFrames =
+ mDisplayPolicy.getSimulatedDisplayFrames(rotation, dw, dh, wmDisplayCutout);
+ final Rect appFrame =
+ mDisplayPolicy.getNonDecorDisplayFrameWithSimulatedFrame(displayFrames);
// AppBounds at the root level should mirror the app screen size.
- outConfig.windowConfiguration.setAppBounds(leftInset /* left */, topInset /* top */,
- leftInset + appWidth /* right */, topInset + appHeight /* bottom */);
+ outConfig.windowConfiguration.setAppBounds(appFrame);
outConfig.windowConfiguration.setRotation(rotation);
outConfig.orientation = (dw <= dh) ? ORIENTATION_PORTRAIT : ORIENTATION_LANDSCAPE;
final float density = mDisplayMetrics.density;
- outConfig.screenWidthDp = (int) (mDisplayPolicy.getConfigDisplayWidth(dw, dh, rotation,
- uiMode, displayCutout) / density + 0.5f);
- outConfig.screenHeightDp = (int) (mDisplayPolicy.getConfigDisplayHeight(dw, dh, rotation,
- uiMode, displayCutout) / density + 0.5f);
+ final Point configSize =
+ mDisplayPolicy.getConfigDisplaySizeWithSimulatedFrame(displayFrames);
+ outConfig.screenWidthDp = (int) (configSize.x / density + 0.5f);
+ outConfig.screenHeightDp = (int) (configSize.y / density + 0.5f);
outConfig.compatScreenWidthDp = (int) (outConfig.screenWidthDp / mCompatibleScreenScale);
outConfig.compatScreenHeightDp = (int) (outConfig.screenHeightDp / mCompatibleScreenScale);
final boolean rotated = (rotation == ROTATION_90 || rotation == ROTATION_270);
- outConfig.compatSmallestScreenWidthDp = computeCompatSmallestWidth(rotated, uiMode, dw, dh);
+ outConfig.compatSmallestScreenWidthDp = computeCompatSmallestWidth(rotated, dw, dh);
outConfig.windowConfiguration.setDisplayRotation(rotation);
}
@@ -2246,7 +2239,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
* Do not call if mDisplayReady == false.
*/
void computeScreenConfiguration(Configuration config) {
- final DisplayInfo displayInfo = updateDisplayAndOrientation(config.uiMode, config);
+ final DisplayInfo displayInfo = updateDisplayAndOrientation(config);
final int dw = displayInfo.logicalWidth;
final int dh = displayInfo.logicalHeight;
mTmpRect.set(0, 0, dw, dh);
@@ -2255,8 +2248,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
config.windowConfiguration.setWindowingMode(getWindowingMode());
config.windowConfiguration.setDisplayWindowingMode(getWindowingMode());
- computeScreenAppConfiguration(config, dw, dh, displayInfo.rotation, config.uiMode,
- displayInfo.displayCutout);
+ computeScreenAppConfiguration(config, dw, dh, displayInfo.rotation,
+ calculateDisplayCutoutForRotation(getRotation()));
config.screenLayout = (config.screenLayout & ~Configuration.SCREENLAYOUT_ROUND_MASK)
| ((displayInfo.flags & Display.FLAG_ROUND) != 0
@@ -2345,7 +2338,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
mWmService.mPolicy.adjustConfigurationLw(config, keyboardPresence, navigationPresence);
}
- private int computeCompatSmallestWidth(boolean rotated, int uiMode, int dw, int dh) {
+ private int computeCompatSmallestWidth(boolean rotated, int dw, int dh) {
mTmpDisplayMetrics.setTo(mDisplayMetrics);
final DisplayMetrics tmpDm = mTmpDisplayMetrics;
final int unrotDw, unrotDh;
@@ -2356,25 +2349,20 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
unrotDw = dw;
unrotDh = dh;
}
- int sw = reduceCompatConfigWidthSize(0, Surface.ROTATION_0, uiMode, tmpDm, unrotDw,
- unrotDh);
- sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_90, uiMode, tmpDm, unrotDh,
- unrotDw);
- sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_180, uiMode, tmpDm, unrotDw,
- unrotDh);
- sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_270, uiMode, tmpDm, unrotDh,
- unrotDw);
+ int sw = reduceCompatConfigWidthSize(0, Surface.ROTATION_0, tmpDm, unrotDw, unrotDh);
+ sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_90, tmpDm, unrotDh, unrotDw);
+ sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_180, tmpDm, unrotDw, unrotDh);
+ sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_270, tmpDm, unrotDh, unrotDw);
return sw;
}
- private int reduceCompatConfigWidthSize(int curSize, int rotation, int uiMode,
+ private int reduceCompatConfigWidthSize(int curSize, int rotation,
DisplayMetrics dm, int dw, int dh) {
- final DisplayCutout displayCutout = calculateDisplayCutoutForRotation(
- rotation).getDisplayCutout();
- dm.noncompatWidthPixels = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode,
- displayCutout);
- dm.noncompatHeightPixels = mDisplayPolicy.getNonDecorDisplayHeight(dh, rotation,
- displayCutout);
+ final WmDisplayCutout wmDisplayCutout = calculateDisplayCutoutForRotation(rotation);
+ final Rect nonDecorSize = mDisplayPolicy.getNonDecorDisplayFrame(dw, dh, rotation,
+ wmDisplayCutout);
+ dm.noncompatWidthPixels = nonDecorSize.width();
+ dm.noncompatHeightPixels = nonDecorSize.height();
float scale = CompatibilityInfo.computeCompatibleScaling(dm, null);
int size = (int)(((dm.noncompatWidthPixels / scale) / dm.density) + .5f);
if (curSize == 0 || size < curSize) {
@@ -2384,7 +2372,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
}
private void computeSizeRangesAndScreenLayout(DisplayInfo displayInfo, boolean rotated,
- int uiMode, int dw, int dh, float density, Configuration outConfig) {
+ int dw, int dh, float density, Configuration outConfig) {
// We need to determine the smallest width that will occur under normal
// operation. To this, start with the base screen size and compute the
@@ -2402,37 +2390,34 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
displayInfo.smallestNominalAppHeight = 1<<30;
displayInfo.largestNominalAppWidth = 0;
displayInfo.largestNominalAppHeight = 0;
- adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_0, uiMode, unrotDw, unrotDh);
- adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_90, uiMode, unrotDh, unrotDw);
- adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_180, uiMode, unrotDw, unrotDh);
- adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_270, uiMode, unrotDh, unrotDw);
+ adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_0, unrotDw, unrotDh);
+ adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_90, unrotDh, unrotDw);
+ adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_180, unrotDw, unrotDh);
+ adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_270, unrotDh, unrotDw);
if (outConfig == null) {
return;
}
int sl = Configuration.resetScreenLayout(outConfig.screenLayout);
- sl = reduceConfigLayout(sl, Surface.ROTATION_0, density, unrotDw, unrotDh, uiMode);
- sl = reduceConfigLayout(sl, Surface.ROTATION_90, density, unrotDh, unrotDw, uiMode);
- sl = reduceConfigLayout(sl, Surface.ROTATION_180, density, unrotDw, unrotDh, uiMode);
- sl = reduceConfigLayout(sl, Surface.ROTATION_270, density, unrotDh, unrotDw, uiMode);
+ sl = reduceConfigLayout(sl, Surface.ROTATION_0, density, unrotDw, unrotDh);
+ sl = reduceConfigLayout(sl, Surface.ROTATION_90, density, unrotDh, unrotDw);
+ sl = reduceConfigLayout(sl, Surface.ROTATION_180, density, unrotDw, unrotDh);
+ sl = reduceConfigLayout(sl, Surface.ROTATION_270, density, unrotDh, unrotDw);
outConfig.smallestScreenWidthDp =
(int) (displayInfo.smallestNominalAppWidth / density + 0.5f);
outConfig.screenLayout = sl;
}
- private int reduceConfigLayout(int curLayout, int rotation, float density, int dw, int dh,
- int uiMode) {
+ private int reduceConfigLayout(int curLayout, int rotation, float density, int dw, int dh) {
// Get the display cutout at this rotation.
- final DisplayCutout displayCutout = calculateDisplayCutoutForRotation(
- rotation).getDisplayCutout();
+ final WmDisplayCutout wmDisplayCutout = calculateDisplayCutoutForRotation(rotation);
// Get the app screen size at this rotation.
- int w = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode, displayCutout);
- int h = mDisplayPolicy.getNonDecorDisplayHeight(dh, rotation, displayCutout);
+ final Rect size = mDisplayPolicy.getNonDecorDisplayFrame(dw, dh, rotation, wmDisplayCutout);
// Compute the screen layout size class for this rotation.
- int longSize = w;
- int shortSize = h;
+ int longSize = size.width();
+ int shortSize = size.height();
if (longSize < shortSize) {
int tmp = longSize;
longSize = shortSize;
@@ -2443,25 +2428,20 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
return Configuration.reduceScreenLayout(curLayout, longSize, shortSize);
}
- private void adjustDisplaySizeRanges(DisplayInfo displayInfo, int rotation,
- int uiMode, int dw, int dh) {
- final DisplayCutout displayCutout = calculateDisplayCutoutForRotation(
- rotation).getDisplayCutout();
- final int width = mDisplayPolicy.getConfigDisplayWidth(dw, dh, rotation, uiMode,
- displayCutout);
- if (width < displayInfo.smallestNominalAppWidth) {
- displayInfo.smallestNominalAppWidth = width;
+ private void adjustDisplaySizeRanges(DisplayInfo displayInfo, int rotation, int dw, int dh) {
+ final WmDisplayCutout wmDisplayCutout = calculateDisplayCutoutForRotation(rotation);
+ final Point size = mDisplayPolicy.getConfigDisplaySize(dw, dh, rotation, wmDisplayCutout);
+ if (size.x < displayInfo.smallestNominalAppWidth) {
+ displayInfo.smallestNominalAppWidth = size.x;
}
- if (width > displayInfo.largestNominalAppWidth) {
- displayInfo.largestNominalAppWidth = width;
+ if (size.x > displayInfo.largestNominalAppWidth) {
+ displayInfo.largestNominalAppWidth = size.x;
}
- final int height = mDisplayPolicy.getConfigDisplayHeight(dw, dh, rotation, uiMode,
- displayCutout);
- if (height < displayInfo.smallestNominalAppHeight) {
- displayInfo.smallestNominalAppHeight = height;
+ if (size.y < displayInfo.smallestNominalAppHeight) {
+ displayInfo.smallestNominalAppHeight = size.y;
}
- if (height > displayInfo.largestNominalAppHeight) {
- displayInfo.largestNominalAppHeight = height;
+ if (size.y > displayInfo.largestNominalAppHeight) {
+ displayInfo.largestNominalAppHeight = size.y;
}
}
@@ -3316,6 +3296,14 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp
mAsyncRotationController.keepAppearanceInPreviousRotation();
}
} else if (isRotationChanging()) {
+ if (displayChange != null) {
+ final boolean seamless = mDisplayRotation.shouldRotateSeamlessly(
+ displayChange.getStartRotation(), displayChange.getEndRotation(),
+ false /* forceUpdate */);
+ if (seamless) {
+ t.onSeamlessRotating(this);
+ }
+ }
mWmService.mLatencyTracker.onActionStart(ACTION_ROTATE_SCREEN);
controller.mTransitionMetricsReporter.associate(t,
startTime -> mWmService.mLatencyTracker.onActionEnd(ACTION_ROTATE_SCREEN));
diff --git a/services/core/java/com/android/server/wm/DisplayPolicy.java b/services/core/java/com/android/server/wm/DisplayPolicy.java
index 1a34c93f2ad6..8e06a810ead1 100644
--- a/services/core/java/com/android/server/wm/DisplayPolicy.java
+++ b/services/core/java/com/android/server/wm/DisplayPolicy.java
@@ -19,15 +19,19 @@ package com.android.server.wm;
import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
import static android.view.Display.TYPE_INTERNAL;
+import static android.view.InsetsState.ITYPE_BOTTOM_DISPLAY_CUTOUT;
import static android.view.InsetsState.ITYPE_BOTTOM_MANDATORY_GESTURES;
import static android.view.InsetsState.ITYPE_BOTTOM_TAPPABLE_ELEMENT;
import static android.view.InsetsState.ITYPE_CAPTION_BAR;
import static android.view.InsetsState.ITYPE_CLIMATE_BAR;
import static android.view.InsetsState.ITYPE_EXTRA_NAVIGATION_BAR;
+import static android.view.InsetsState.ITYPE_LEFT_DISPLAY_CUTOUT;
import static android.view.InsetsState.ITYPE_LEFT_GESTURES;
import static android.view.InsetsState.ITYPE_NAVIGATION_BAR;
+import static android.view.InsetsState.ITYPE_RIGHT_DISPLAY_CUTOUT;
import static android.view.InsetsState.ITYPE_RIGHT_GESTURES;
import static android.view.InsetsState.ITYPE_STATUS_BAR;
+import static android.view.InsetsState.ITYPE_TOP_DISPLAY_CUTOUT;
import static android.view.InsetsState.ITYPE_TOP_MANDATORY_GESTURES;
import static android.view.InsetsState.ITYPE_TOP_TAPPABLE_ELEMENT;
import static android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS;
@@ -103,6 +107,7 @@ import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Insets;
import android.graphics.PixelFormat;
+import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Region;
import android.gui.DropInputMode;
@@ -127,6 +132,8 @@ import android.view.InsetsSource;
import android.view.InsetsState;
import android.view.InsetsState.InternalInsetsType;
import android.view.InsetsVisibilities;
+import android.view.PrivacyIndicatorBounds;
+import android.view.RoundedCorners;
import android.view.Surface;
import android.view.View;
import android.view.ViewDebug;
@@ -136,7 +143,6 @@ import android.view.WindowLayout;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.WindowManagerGlobal;
-import android.view.WindowManagerPolicyConstants;
import android.view.accessibility.AccessibilityManager;
import android.window.ClientWindowFrames;
@@ -160,6 +166,7 @@ import com.android.server.policy.WindowManagerPolicy.ScreenOnListener;
import com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs;
import com.android.server.statusbar.StatusBarManagerInternal;
import com.android.server.wallpaper.WallpaperManagerInternal;
+import com.android.server.wm.utils.WmDisplayCutout;
import java.io.PrintWriter;
import java.util.ArrayList;
@@ -383,6 +390,16 @@ public class DisplayPolicy {
private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS = 0;
private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION = 1;
+ // TODO (b/235842600): Use public type once we can treat task bar as navigation bar.
+ private static final int[] STABLE_TYPES = new int[]{
+ ITYPE_TOP_DISPLAY_CUTOUT, ITYPE_RIGHT_DISPLAY_CUTOUT, ITYPE_BOTTOM_DISPLAY_CUTOUT,
+ ITYPE_LEFT_DISPLAY_CUTOUT, ITYPE_NAVIGATION_BAR, ITYPE_STATUS_BAR, ITYPE_CLIMATE_BAR
+ };
+ private static final int[] NON_DECOR_TYPES = new int[]{
+ ITYPE_TOP_DISPLAY_CUTOUT, ITYPE_RIGHT_DISPLAY_CUTOUT, ITYPE_BOTTOM_DISPLAY_CUTOUT,
+ ITYPE_LEFT_DISPLAY_CUTOUT, ITYPE_NAVIGATION_BAR
+ };
+
private final GestureNavigationSettingsObserver mGestureNavigationSettingsObserver;
private final WindowManagerInternal.AppTransitionListener mAppTransitionListener;
@@ -2007,35 +2024,6 @@ public class DisplayPolicy {
return mUiContext;
}
- private int getNavigationBarWidth(int rotation, int uiMode, int position) {
- if (mNavigationBar == null) {
- return 0;
- }
- LayoutParams lp = mNavigationBar.mAttrs;
- if (lp.paramsForRotation != null
- && lp.paramsForRotation.length == 4
- && lp.paramsForRotation[rotation] != null) {
- lp = lp.paramsForRotation[rotation];
- }
- Insets providedInsetsSize = null;
- if (lp.providedInsets != null) {
- for (InsetsFrameProvider provider : lp.providedInsets) {
- if (provider.type != ITYPE_NAVIGATION_BAR) {
- continue;
- }
- providedInsetsSize = provider.insetsSize;
- }
- }
- if (providedInsetsSize != null) {
- if (position == NAV_BAR_LEFT) {
- return providedInsetsSize.left;
- } else if (position == NAV_BAR_RIGHT) {
- return providedInsetsSize.right;
- }
- }
- return lp.width;
- }
-
@VisibleForTesting
void setCanSystemBarsBeShownByUser(boolean canBeShown) {
mCanSystemBarsBeShownByUser = canBeShown;
@@ -2057,45 +2045,24 @@ public class DisplayPolicy {
}
/**
- * Return the display width available after excluding any screen
- * decorations that could never be removed in Honeycomb. That is, system bar or
- * button bar.
+ * Return the display frame available after excluding any screen decorations that could never be
+ * removed in Honeycomb. That is, system bar or button bar.
+ *
+ * @return display frame excluding all non-decor insets.
*/
- public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation, int uiMode,
- DisplayCutout displayCutout) {
- int width = fullWidth;
- if (hasNavigationBar()) {
- final int navBarPosition = navigationBarPosition(rotation);
- if (navBarPosition == NAV_BAR_LEFT || navBarPosition == NAV_BAR_RIGHT) {
- width -= getNavigationBarWidth(rotation, uiMode, navBarPosition);
- }
- }
- if (displayCutout != null) {
- width -= displayCutout.getSafeInsetLeft() + displayCutout.getSafeInsetRight();
- }
- return width;
+ Rect getNonDecorDisplayFrame(int fullWidth, int fullHeight, int rotation,
+ WmDisplayCutout cutout) {
+ final DisplayFrames displayFrames =
+ getSimulatedDisplayFrames(rotation, fullWidth, fullHeight, cutout);
+ return getNonDecorDisplayFrameWithSimulatedFrame(displayFrames);
}
- @VisibleForTesting
- int getNavigationBarHeight(int rotation) {
- if (mNavigationBar == null) {
- return 0;
- }
- LayoutParams lp = mNavigationBar.mAttrs.forRotation(rotation);
- Insets providedInsetsSize = null;
- if (lp.providedInsets != null) {
- for (InsetsFrameProvider provider : lp.providedInsets) {
- if (provider.type != ITYPE_NAVIGATION_BAR) {
- continue;
- }
- providedInsetsSize = provider.insetsSize;
- if (providedInsetsSize != null) {
- return providedInsetsSize.bottom;
- }
- break;
- }
- }
- return lp.height;
+ Rect getNonDecorDisplayFrameWithSimulatedFrame(DisplayFrames displayFrames) {
+ final Rect nonDecorInsets =
+ getInsetsWithInternalTypes(displayFrames, NON_DECOR_TYPES).toRect();
+ final Rect displayFrame = new Rect(displayFrames.mInsetsState.getDisplayFrame());
+ displayFrame.inset(nonDecorInsets);
+ return displayFrame;
}
/**
@@ -2117,53 +2084,23 @@ public class DisplayPolicy {
}
/**
- * Return the display height available after excluding any screen
- * decorations that could never be removed in Honeycomb. That is, system bar or
- * button bar.
- */
- public int getNonDecorDisplayHeight(int fullHeight, int rotation, DisplayCutout displayCutout) {
- int height = fullHeight;
- final int navBarPosition = navigationBarPosition(rotation);
- if (navBarPosition == NAV_BAR_BOTTOM) {
- height -= getNavigationBarHeight(rotation);
- }
- if (displayCutout != null) {
- height -= displayCutout.getSafeInsetTop() + displayCutout.getSafeInsetBottom();
- }
- return height;
- }
-
- /**
- * Return the available screen width that we should report for the
+ * Return the available screen size that we should report for the
* configuration. This must be no larger than
- * {@link #getNonDecorDisplayWidth(int, int, int, int, DisplayCutout)}; it may be smaller
+ * {@link #getNonDecorDisplayFrame(int, int, int, DisplayCutout)}; it may be smaller
* than that to account for more transient decoration like a status bar.
*/
- public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation, int uiMode,
- DisplayCutout displayCutout) {
- return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation, uiMode, displayCutout);
+ public Point getConfigDisplaySize(int fullWidth, int fullHeight, int rotation,
+ WmDisplayCutout wmDisplayCutout) {
+ final DisplayFrames displayFrames = getSimulatedDisplayFrames(rotation, fullWidth,
+ fullHeight, wmDisplayCutout);
+ return getConfigDisplaySizeWithSimulatedFrame(displayFrames);
}
- /**
- * Return the available screen height that we should report for the
- * configuration. This must be no larger than
- * {@link #getNonDecorDisplayHeight(int, int, DisplayCutout)}; it may be smaller
- * than that to account for more transient decoration like a status bar.
- */
- public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation, int uiMode,
- DisplayCutout displayCutout) {
- // There is a separate status bar at the top of the display. We don't count that as part
- // of the fixed decor, since it can hide; however, for purposes of configurations,
- // we do want to exclude it since applications can't generally use that part
- // of the screen.
- int statusBarHeight = mStatusBarHeightForRotation[rotation];
- if (displayCutout != null) {
- // If there is a cutout, it may already have accounted for some part of the status
- // bar height.
- statusBarHeight = Math.max(0, statusBarHeight - displayCutout.getSafeInsetTop());
- }
- return getNonDecorDisplayHeight(fullHeight, rotation, displayCutout)
- - statusBarHeight;
+ Point getConfigDisplaySizeWithSimulatedFrame(DisplayFrames displayFrames) {
+ final Insets insets = getInsetsWithInternalTypes(displayFrames, STABLE_TYPES);
+ Rect configFrame = new Rect(displayFrames.mInsetsState.getDisplayFrame());
+ configFrame.inset(insets);
+ return new Point(configFrame.width(), configFrame.height());
}
/**
@@ -2195,48 +2132,75 @@ public class DisplayPolicy {
* Calculates the stable insets without running a layout.
*
* @param displayRotation the current display rotation
+ * @param displayWidth full display width
+ * @param displayHeight full display height
* @param displayCutout the current display cutout
* @param outInsets the insets to return
*/
- public void getStableInsetsLw(int displayRotation, DisplayCutout displayCutout,
- Rect outInsets) {
- outInsets.setEmpty();
+ public void getStableInsetsLw(int displayRotation, int displayWidth, int displayHeight,
+ WmDisplayCutout displayCutout, Rect outInsets) {
+ final DisplayFrames displayFrames = getSimulatedDisplayFrames(displayRotation,
+ displayWidth, displayHeight, displayCutout);
+ getStableInsetsWithSimulatedFrame(displayFrames, outInsets);
+ }
- // Navigation bar and status bar.
- getNonDecorInsetsLw(displayRotation, displayCutout, outInsets);
- convertNonDecorInsetsToStableInsets(outInsets, displayRotation);
+ void getStableInsetsWithSimulatedFrame(DisplayFrames displayFrames, Rect outInsets) {
+ // Navigation bar, status bar, and cutout.
+ outInsets.set(getInsetsWithInternalTypes(displayFrames, STABLE_TYPES).toRect());
}
/**
* Calculates the insets for the areas that could never be removed in Honeycomb, i.e. system
- * bar or button bar. See {@link #getNonDecorDisplayWidth}.
- * @param displayRotation the current display rotation
- * @param displayCutout the current display cutout
+ * bar or button bar. See {@link #getNonDecorDisplayFrame}.
+ *
+ * @param displayRotation the current display rotation
+ * @param fullWidth the width of the display, including all insets
+ * @param fullHeight the height of the display, including all insets
+ * @param cutout the current display cutout
* @param outInsets the insets to return
*/
- public void getNonDecorInsetsLw(int displayRotation, DisplayCutout displayCutout,
- Rect outInsets) {
- outInsets.setEmpty();
-
- // Only navigation bar
- if (hasNavigationBar()) {
- final int uiMode = mService.mPolicy.getUiMode();
- int position = navigationBarPosition(displayRotation);
- if (position == NAV_BAR_BOTTOM) {
- outInsets.bottom = getNavigationBarHeight(displayRotation);
- } else if (position == NAV_BAR_RIGHT) {
- outInsets.right = getNavigationBarWidth(displayRotation, uiMode, position);
- } else if (position == NAV_BAR_LEFT) {
- outInsets.left = getNavigationBarWidth(displayRotation, uiMode, position);
- }
- }
+ public void getNonDecorInsetsLw(int displayRotation, int fullWidth, int fullHeight,
+ WmDisplayCutout cutout, Rect outInsets) {
+ final DisplayFrames displayFrames =
+ getSimulatedDisplayFrames(displayRotation, fullWidth, fullHeight, cutout);
+ getNonDecorInsetsWithSimulatedFrame(displayFrames, outInsets);
+ }
+
+ void getNonDecorInsetsWithSimulatedFrame(DisplayFrames displayFrames, Rect outInsets) {
+ outInsets.set(getInsetsWithInternalTypes(displayFrames, NON_DECOR_TYPES).toRect());
+ }
+
+ DisplayFrames getSimulatedDisplayFrames(int displayRotation, int fullWidth,
+ int fullHeight, WmDisplayCutout cutout) {
+ final DisplayInfo info = new DisplayInfo(mDisplayContent.getDisplayInfo());
+ info.rotation = displayRotation;
+ info.logicalWidth = fullWidth;
+ info.logicalHeight = fullHeight;
+ info.displayCutout = cutout.getDisplayCutout();
+ final RoundedCorners roundedCorners =
+ mDisplayContent.calculateRoundedCornersForRotation(displayRotation);
+ final PrivacyIndicatorBounds indicatorBounds =
+ mDisplayContent.calculatePrivacyIndicatorBoundsForRotation(displayRotation);
+ final DisplayFrames displayFrames = new DisplayFrames(getDisplayId(), new InsetsState(),
+ info, cutout, roundedCorners, indicatorBounds);
+ simulateLayoutDisplay(displayFrames);
+ return displayFrames;
+ }
- if (displayCutout != null) {
- outInsets.left += displayCutout.getSafeInsetLeft();
- outInsets.top += displayCutout.getSafeInsetTop();
- outInsets.right += displayCutout.getSafeInsetRight();
- outInsets.bottom += displayCutout.getSafeInsetBottom();
- }
+ @VisibleForTesting
+ Insets getInsets(DisplayFrames displayFrames, @InsetsType int type) {
+ final InsetsState state = displayFrames.mInsetsState;
+ final Insets insets = state.calculateInsets(state.getDisplayFrame(), type,
+ true /* ignoreVisibility */);
+ return insets;
+ }
+
+ Insets getInsetsWithInternalTypes(DisplayFrames displayFrames,
+ @InternalInsetsType int[] types) {
+ final InsetsState state = displayFrames.mInsetsState;
+ final Insets insets = state.calculateInsetsWithInternalTypes(state.getDisplayFrame(), types,
+ true /* ignoreVisibility */);
+ return insets;
}
@NavigationBarPosition
@@ -2256,17 +2220,6 @@ public class DisplayPolicy {
}
/**
- * @return The side of the screen where navigation bar is positioned.
- * @see WindowManagerPolicyConstants#NAV_BAR_LEFT
- * @see WindowManagerPolicyConstants#NAV_BAR_RIGHT
- * @see WindowManagerPolicyConstants#NAV_BAR_BOTTOM
- */
- @NavigationBarPosition
- public int getNavBarPosition() {
- return mNavigationBarPosition;
- }
-
- /**
* A new window has been focused.
*/
public void focusChangedLw(WindowState lastFocus, WindowState newFocus) {
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 384a4d17c752..e38f5fe61888 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -1883,8 +1883,7 @@ class Task extends TaskFragment {
}
final int newWinMode = getWindowingMode();
- if ((prevWinMode != newWinMode) && (mDisplayContent != null)
- && shouldStartChangeTransition(prevWinMode, newWinMode)) {
+ if (shouldStartChangeTransition(prevWinMode, mTmpPrevBounds)) {
initializeChangeTransition(mTmpPrevBounds);
}
@@ -2135,10 +2134,16 @@ class Task extends TaskFragment {
bounds.offset(horizontalDiff, verticalDiff);
}
- private boolean shouldStartChangeTransition(int prevWinMode, int newWinMode) {
+ private boolean shouldStartChangeTransition(int prevWinMode, @NonNull Rect prevBounds) {
if (!isLeafTask() || !canStartChangeTransition()) {
return false;
}
+ final int newWinMode = getWindowingMode();
+ if (mTransitionController.inTransition(this)) {
+ final Rect newBounds = getConfiguration().windowConfiguration.getBounds();
+ return prevWinMode != newWinMode || prevBounds.width() != newBounds.width()
+ || prevBounds.height() != newBounds.height();
+ }
// Only do an animation into and out-of freeform mode for now. Other mode
// transition animations are currently handled by system-ui.
return (prevWinMode == WINDOWING_MODE_FREEFORM) != (newWinMode == WINDOWING_MODE_FREEFORM);
diff --git a/services/core/java/com/android/server/wm/TaskFragment.java b/services/core/java/com/android/server/wm/TaskFragment.java
index 1b7c6d25f9c6..8872b3526e8c 100644
--- a/services/core/java/com/android/server/wm/TaskFragment.java
+++ b/services/core/java/com/android/server/wm/TaskFragment.java
@@ -98,6 +98,7 @@ import com.android.internal.util.function.pooled.PooledLambda;
import com.android.internal.util.function.pooled.PooledPredicate;
import com.android.server.am.HostingRecord;
import com.android.server.pm.parsing.pkg.AndroidPackage;
+import com.android.server.wm.utils.WmDisplayCutout;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -2208,11 +2209,13 @@ class TaskFragment extends WindowContainer<WindowContainer> {
mTmpBounds.set(0, 0, displayInfo.logicalWidth, displayInfo.logicalHeight);
final DisplayPolicy policy = rootTask.mDisplayContent.getDisplayPolicy();
- policy.getNonDecorInsetsLw(displayInfo.rotation,
- displayInfo.displayCutout, mTmpInsets);
+ final WmDisplayCutout cutout =
+ rootTask.mDisplayContent.calculateDisplayCutoutForRotation(displayInfo.rotation);
+ final DisplayFrames displayFrames = policy.getSimulatedDisplayFrames(displayInfo.rotation,
+ displayInfo.logicalWidth, displayInfo.logicalHeight, cutout);
+ policy.getNonDecorInsetsWithSimulatedFrame(displayFrames, mTmpInsets);
intersectWithInsetsIfFits(outNonDecorBounds, mTmpBounds, mTmpInsets);
-
- policy.convertNonDecorInsetsToStableInsets(mTmpInsets, displayInfo.rotation);
+ policy.getStableInsetsWithSimulatedFrame(displayFrames, mTmpInsets);
intersectWithInsetsIfFits(outStableBounds, mTmpBounds, mTmpInsets);
}
diff --git a/services/core/java/com/android/server/wm/Transition.java b/services/core/java/com/android/server/wm/Transition.java
index 2d3e437bed60..80b7514d3502 100644
--- a/services/core/java/com/android/server/wm/Transition.java
+++ b/services/core/java/com/android/server/wm/Transition.java
@@ -16,6 +16,7 @@
package com.android.server.wm;
+import static android.app.ActivityOptions.ANIM_OPEN_CROSS_PROFILE_APPS;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
@@ -68,6 +69,7 @@ import android.app.ActivityManager;
import android.content.pm.ActivityInfo;
import android.graphics.Point;
import android.graphics.Rect;
+import android.hardware.HardwareBuffer;
import android.os.Binder;
import android.os.IBinder;
import android.os.IRemoteCallback;
@@ -205,6 +207,9 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
/** @see #setCanPipOnFinish */
private boolean mCanPipOnFinish = true;
+ private boolean mIsSeamlessRotation = false;
+ private IContainerFreezer mContainerFreezer = null;
+
Transition(@TransitionType int type, @TransitionFlags int flags,
TransitionController controller, BLASTSyncEngine syncEngine) {
mType = type;
@@ -265,10 +270,31 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
return mTargetDisplays.contains(dc);
}
+ /** Set a transition to be a seamless-rotation. */
void setSeamlessRotation(@NonNull WindowContainer wc) {
final ChangeInfo info = mChanges.get(wc);
if (info == null) return;
info.mFlags = info.mFlags | ChangeInfo.FLAG_SEAMLESS_ROTATION;
+ onSeamlessRotating(wc.getDisplayContent());
+ }
+
+ /**
+ * Called when it's been determined that this is transition is a seamless rotation. This should
+ * be called before any WM changes have happened.
+ */
+ void onSeamlessRotating(@NonNull DisplayContent dc) {
+ // Don't need to do anything special if everything is using BLAST sync already.
+ if (mSyncEngine.getSyncSet(mSyncId).mSyncMethod == BLASTSyncEngine.METHOD_BLAST) return;
+ if (mContainerFreezer == null) {
+ mContainerFreezer = new ScreenshotFreezer();
+ }
+ mIsSeamlessRotation = true;
+ final WindowState top = dc.getDisplayPolicy().getTopFullscreenOpaqueWindow();
+ if (top != null) {
+ top.mSyncMethodOverride = BLASTSyncEngine.METHOD_BLAST;
+ ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS, "Override sync-method for %s "
+ + "because seamless rotating", top.getName());
+ }
}
/**
@@ -285,6 +311,11 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
}
}
+ /** Only for testing. */
+ void setContainerFreezer(IContainerFreezer freezer) {
+ mContainerFreezer = freezer;
+ }
+
@TransitionState
int getState() {
return mState;
@@ -314,13 +345,18 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
return mState == STATE_COLLECTING || mState == STATE_STARTED;
}
- /** Starts collecting phase. Once this starts, all relevant surface operations are sync. */
+ @VisibleForTesting
void startCollecting(long timeoutMs) {
+ startCollecting(timeoutMs, TransitionController.SYNC_METHOD);
+ }
+
+ /** Starts collecting phase. Once this starts, all relevant surface operations are sync. */
+ void startCollecting(long timeoutMs, int method) {
if (mState != STATE_PENDING) {
throw new IllegalStateException("Attempting to re-use a transition");
}
mState = STATE_COLLECTING;
- mSyncId = mSyncEngine.startSyncSet(this, timeoutMs, TAG);
+ mSyncId = mSyncEngine.startSyncSet(this, timeoutMs, TAG, method);
mController.mTransitionTracer.logState(this);
}
@@ -415,6 +451,37 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
}
/**
+ * Records that a particular container is changing visibly (ie. something about it is changing
+ * while it remains visible). This only effects windows that are already in the collecting
+ * transition.
+ */
+ void collectVisibleChange(WindowContainer wc) {
+ if (mSyncEngine.getSyncSet(mSyncId).mSyncMethod == BLASTSyncEngine.METHOD_BLAST) {
+ // All windows are synced already.
+ return;
+ }
+ if (!isInTransition(wc)) return;
+
+ if (mContainerFreezer == null) {
+ mContainerFreezer = new ScreenshotFreezer();
+ }
+ Transition.ChangeInfo change = mChanges.get(wc);
+ if (change == null || !change.mVisible || !wc.isVisibleRequested()) return;
+ // Note: many more tests have already been done by caller.
+ mContainerFreezer.freeze(wc, change.mAbsoluteBounds);
+ }
+
+ /**
+ * @return {@code true} if `wc` is a participant or is a descendant of one.
+ */
+ boolean isInTransition(WindowContainer wc) {
+ for (WindowContainer p = wc; p != null; p = p.getParent()) {
+ if (mParticipants.contains(p)) return true;
+ }
+ return false;
+ }
+
+ /**
* Specifies configuration change explicitly for the window container, so it can be chosen as
* transition target. This is usually used with transition mode
* {@link android.view.WindowManager#TRANSIT_CHANGE}.
@@ -531,6 +598,10 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
displays.add(target.getDisplayContent());
}
}
+ // Remove screenshot layers if necessary
+ if (mContainerFreezer != null) {
+ mContainerFreezer.cleanUp(t);
+ }
// Need to update layers on involved displays since they were all paused while
// the animation played. This puts the layers back into the correct order.
mController.mBuildingFinishLayers = true;
@@ -817,6 +888,19 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
transaction);
if (mOverrideOptions != null) {
info.setAnimationOptions(mOverrideOptions);
+ if (mOverrideOptions.getType() == ANIM_OPEN_CROSS_PROFILE_APPS) {
+ for (int i = 0; i < mTargets.size(); ++i) {
+ final TransitionInfo.Change c = info.getChanges().get(i);
+ final ActivityRecord ar = mTargets.get(i).asActivityRecord();
+ if (ar == null || c.getMode() != TRANSIT_OPEN) continue;
+ int flags = c.getFlags();
+ flags |= ar.mUserId == ar.mWmService.mCurrentUserId
+ ? TransitionInfo.FLAG_CROSS_PROFILE_OWNER_THUMBNAIL
+ : TransitionInfo.FLAG_CROSS_PROFILE_WORK_THUMBNAIL;
+ c.setFlags(flags);
+ break;
+ }
+ }
}
// TODO(b/188669821): Move to animation impl in shell.
@@ -1982,4 +2066,111 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe
return sortedTargets;
}
}
+
+ /**
+ * Interface for freezing a container's content during sync preparation. Really just one impl
+ * but broken into an interface for testing (since you can't take screenshots in unit tests).
+ */
+ interface IContainerFreezer {
+ /**
+ * Makes sure a particular window is "frozen" for the remainder of a sync.
+ *
+ * @return whether the freeze was successful. It fails if `wc` is already in a frozen window
+ * or is not visible/ready.
+ */
+ boolean freeze(@NonNull WindowContainer wc, @NonNull Rect bounds);
+
+ /** Populates `t` with operations that clean-up any state created to set-up the freeze. */
+ void cleanUp(SurfaceControl.Transaction t);
+ }
+
+ /**
+ * Freezes container content by taking a screenshot. Because screenshots are heavy, usage of
+ * any container "freeze" is currently explicit. WM code needs to be prudent about which
+ * containers to freeze.
+ */
+ @VisibleForTesting
+ private class ScreenshotFreezer implements IContainerFreezer {
+ /** Values are the screenshot "surfaces" or null if it was frozen via BLAST override. */
+ private final ArrayMap<WindowContainer, SurfaceControl> mSnapshots = new ArrayMap<>();
+
+ /** Takes a screenshot and puts it at the top of the container's surface. */
+ @Override
+ public boolean freeze(@NonNull WindowContainer wc, @NonNull Rect bounds) {
+ if (!wc.isVisibleRequested()) return false;
+
+ // Check if any parents have already been "frozen". If so, `wc` is already part of that
+ // snapshot, so just skip it.
+ for (WindowContainer p = wc; p != null; p = p.getParent()) {
+ if (mSnapshots.containsKey(p)) return false;
+ }
+
+ if (mIsSeamlessRotation) {
+ WindowState top = wc.getDisplayContent() == null ? null
+ : wc.getDisplayContent().getDisplayPolicy().getTopFullscreenOpaqueWindow();
+ if (top != null && (top == wc || top.isDescendantOf(wc))) {
+ // Don't use screenshots for seamless windows: these will use BLAST even if not
+ // BLAST mode.
+ mSnapshots.put(wc, null);
+ return true;
+ }
+ }
+
+ ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS, "Screenshotting %s [%s]",
+ wc.toString(), bounds.toString());
+
+ Rect cropBounds = new Rect(bounds);
+ cropBounds.offsetTo(0, 0);
+ SurfaceControl.LayerCaptureArgs captureArgs =
+ new SurfaceControl.LayerCaptureArgs.Builder(wc.getSurfaceControl())
+ .setSourceCrop(cropBounds)
+ .setCaptureSecureLayers(true)
+ .setAllowProtected(true)
+ .build();
+ SurfaceControl.ScreenshotHardwareBuffer screenshotBuffer =
+ SurfaceControl.captureLayers(captureArgs);
+ final HardwareBuffer buffer = screenshotBuffer == null ? null
+ : screenshotBuffer.getHardwareBuffer();
+ if (buffer == null || buffer.getWidth() <= 1 || buffer.getHeight() <= 1) {
+ // This can happen when display is not ready.
+ Slog.w(TAG, "Failed to capture screenshot for " + wc);
+ return false;
+ }
+ SurfaceControl snapshotSurface = wc.makeAnimationLeash()
+ .setName("transition snapshot: " + wc.toString())
+ .setOpaque(true)
+ .setParent(wc.getSurfaceControl())
+ .setSecure(screenshotBuffer.containsSecureLayers())
+ .setCallsite("Transition.ScreenshotSync")
+ .setBLASTLayer()
+ .build();
+ mSnapshots.put(wc, snapshotSurface);
+ SurfaceControl.Transaction t = wc.mWmService.mTransactionFactory.get();
+
+ t.setBuffer(snapshotSurface, buffer);
+ t.setDataSpace(snapshotSurface, screenshotBuffer.getColorSpace().getDataSpace());
+ t.show(snapshotSurface);
+
+ // Place it on top of anything else in the container.
+ t.setLayer(snapshotSurface, Integer.MAX_VALUE);
+ t.apply();
+ t.close();
+
+ // Detach the screenshot on the sync transaction (the screenshot is just meant to
+ // freeze the window until the sync transaction is applied (with all its other
+ // corresponding changes), so this is how we unfreeze it.
+ wc.getSyncTransaction().reparent(snapshotSurface, null /* newParent */);
+ return true;
+ }
+
+ @Override
+ public void cleanUp(SurfaceControl.Transaction t) {
+ for (int i = 0; i < mSnapshots.size(); ++i) {
+ SurfaceControl snap = mSnapshots.valueAt(i);
+ // May be null if it was frozen via BLAST override.
+ if (snap == null) continue;
+ t.remove(snap);
+ }
+ }
+ }
}
diff --git a/services/core/java/com/android/server/wm/TransitionController.java b/services/core/java/com/android/server/wm/TransitionController.java
index 846aa3e3739a..f62efbfbd08d 100644
--- a/services/core/java/com/android/server/wm/TransitionController.java
+++ b/services/core/java/com/android/server/wm/TransitionController.java
@@ -46,6 +46,7 @@ import android.window.TransitionInfo;
import android.window.TransitionRequestInfo;
import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.protolog.ProtoLogGroup;
import com.android.internal.protolog.common.ProtoLog;
import com.android.server.LocalServices;
@@ -64,6 +65,11 @@ class TransitionController {
private static final boolean SHELL_TRANSITIONS_ROTATION =
SystemProperties.getBoolean("persist.wm.debug.shell_transit_rotate", false);
+ /** Which sync method to use for transition syncs. */
+ static final int SYNC_METHOD =
+ android.os.SystemProperties.getBoolean("persist.wm.debug.shell_transit_blast", true)
+ ? BLASTSyncEngine.METHOD_BLAST : BLASTSyncEngine.METHOD_NONE;
+
/** The same as legacy APP_TRANSITION_TIMEOUT_MS. */
private static final int DEFAULT_TIMEOUT_MS = 5000;
/** Less duration for CHANGE type because it does not involve app startup. */
@@ -160,6 +166,12 @@ class TransitionController {
/** Starts Collecting */
void moveToCollecting(@NonNull Transition transition) {
+ moveToCollecting(transition, SYNC_METHOD);
+ }
+
+ /** Starts Collecting */
+ @VisibleForTesting
+ void moveToCollecting(@NonNull Transition transition, int method) {
if (mCollectingTransition != null) {
throw new IllegalStateException("Simultaneous transition collection not supported.");
}
@@ -167,7 +179,7 @@ class TransitionController {
// Distinguish change type because the response time is usually expected to be not too long.
final long timeoutMs =
transition.mType == TRANSIT_CHANGE ? CHANGE_TIMEOUT_MS : DEFAULT_TIMEOUT_MS;
- mCollectingTransition.startCollecting(timeoutMs);
+ mCollectingTransition.startCollecting(timeoutMs, method);
ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS, "Start collecting in Transition: %s",
mCollectingTransition);
dispatchLegacyAppTransitionPending();
@@ -228,10 +240,7 @@ class TransitionController {
*/
boolean inCollectingTransition(@NonNull WindowContainer wc) {
if (!isCollecting()) return false;
- for (WindowContainer p = wc; p != null; p = p.getParent()) {
- if (mCollectingTransition.mParticipants.contains(p)) return true;
- }
- return false;
+ return mCollectingTransition.isInTransition(wc);
}
/**
@@ -247,9 +256,7 @@ class TransitionController {
*/
boolean inPlayingTransition(@NonNull WindowContainer wc) {
for (int i = mPlayingTransitions.size() - 1; i >= 0; --i) {
- for (WindowContainer p = wc; p != null; p = p.getParent()) {
- if (mPlayingTransitions.get(i).mParticipants.contains(p)) return true;
- }
+ if (mPlayingTransitions.get(i).isInTransition(wc)) return true;
}
return false;
}
@@ -469,6 +476,7 @@ class TransitionController {
void collectForDisplayAreaChange(@NonNull DisplayArea<?> wc) {
final Transition transition = mCollectingTransition;
if (transition == null || !transition.mParticipants.contains(wc)) return;
+ transition.collectVisibleChange(wc);
// Collect all visible tasks.
wc.forAllLeafTasks(task -> {
if (task.isVisible()) {
@@ -488,6 +496,16 @@ class TransitionController {
}
}
+ /**
+ * Records that a particular container is changing visibly (ie. something about it is changing
+ * while it remains visible). This only effects windows that are already in the collecting
+ * transition.
+ */
+ void collectVisibleChange(WindowContainer wc) {
+ if (!isCollecting()) return;
+ mCollectingTransition.collectVisibleChange(wc);
+ }
+
/** @see Transition#mStatusBarTransitionDelay */
void setStatusBarTransitionDelay(long delay) {
if (mCollectingTransition == null) return;
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index 73658b2dc301..d820ec44ebf6 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -343,6 +343,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
BLASTSyncEngine.SyncGroup mSyncGroup = null;
final SurfaceControl.Transaction mSyncTransaction;
@SyncState int mSyncState = SYNC_STATE_NONE;
+ int mSyncMethodOverride = BLASTSyncEngine.METHOD_UNDEFINED;
private final List<WindowContainerListener> mListeners = new ArrayList<>();
@@ -2829,6 +2830,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
*/
void initializeChangeTransition(Rect startBounds, @Nullable SurfaceControl freezeTarget) {
if (mDisplayContent.mTransitionController.isShellTransitionsEnabled()) {
+ mDisplayContent.mTransitionController.collectVisibleChange(this);
// TODO(b/207070762): request shell transition for activityEmbedding change.
return;
}
@@ -3662,6 +3664,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
boolean onSyncFinishedDrawing() {
if (mSyncState == SYNC_STATE_NONE) return false;
mSyncState = SYNC_STATE_READY;
+ mSyncMethodOverride = BLASTSyncEngine.METHOD_UNDEFINED;
mWmService.mWindowPlacerLocked.requestTraversal();
ProtoLog.v(WM_DEBUG_SYNC_ENGINE, "onSyncFinishedDrawing %s", this);
return true;
@@ -3680,6 +3683,13 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
mSyncGroup = group;
}
+ @Nullable
+ BLASTSyncEngine.SyncGroup getSyncGroup() {
+ if (mSyncGroup != null) return mSyncGroup;
+ if (mParent != null) return mParent.getSyncGroup();
+ return null;
+ }
+
/**
* Prepares this container for participation in a sync-group. This includes preparing all its
* children.
@@ -3719,6 +3729,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
}
if (cancel && mSyncGroup != null) mSyncGroup.onCancelSync(this);
mSyncState = SYNC_STATE_NONE;
+ mSyncMethodOverride = BLASTSyncEngine.METHOD_UNDEFINED;
mSyncGroup = null;
}
@@ -3821,6 +3832,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer<
// disable this when shell transitions is disabled.
if (mTransitionController.isShellTransitionsEnabled()) {
mSyncState = SYNC_STATE_NONE;
+ mSyncMethodOverride = BLASTSyncEngine.METHOD_UNDEFINED;
}
prepareSync();
}
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 22411bb068a0..b4386f6ad206 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -92,7 +92,6 @@ import static android.view.WindowManager.fixScale;
import static android.view.WindowManagerGlobal.ADD_OKAY;
import static android.view.WindowManagerGlobal.RELAYOUT_RES_CANCEL_AND_REDRAW;
import static android.view.WindowManagerGlobal.RELAYOUT_RES_SURFACE_CHANGED;
-import static android.view.WindowManagerPolicyConstants.NAV_BAR_INVALID;
import static android.view.WindowManagerPolicyConstants.TYPE_LAYER_MULTIPLIER;
import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_MISSING_WINDOW;
import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_NOT_VISIBLE_ON_SCREEN;
@@ -321,6 +320,7 @@ import com.android.server.policy.WindowManagerPolicy;
import com.android.server.policy.WindowManagerPolicy.ScreenOffListener;
import com.android.server.power.ShutdownThread;
import com.android.server.utils.PriorityDump;
+import com.android.server.wm.utils.WmDisplayCutout;
import dalvik.annotation.optimization.NeverCompile;
@@ -1873,7 +1873,8 @@ public class WindowManagerService extends IWindowManager.Stub
ProtoLog.v(WM_DEBUG_ADD_REMOVE, "addWindow: New client %s"
+ ": window=%s Callers=%s", client.asBinder(), win, Debug.getCallers(5));
- if (win.isVisibleRequestedOrAdding() && displayContent.updateOrientation()) {
+ if ((win.isVisibleRequestedOrAdding() && displayContent.updateOrientation())
+ || win.providesNonDecorInsets()) {
displayContent.sendNewConfiguration();
}
@@ -2583,7 +2584,7 @@ public class WindowManagerService extends IWindowManager.Stub
final int maybeSyncSeqId;
if (USE_BLAST_SYNC && win.useBLASTSync() && viewVisibility != View.GONE
&& win.mSyncSeqId > lastSyncSeqId) {
- maybeSyncSeqId = win.mSyncSeqId;
+ maybeSyncSeqId = win.shouldSyncWithBuffers() ? win.mSyncSeqId : -1;
win.markRedrawForSyncReported();
} else {
maybeSyncSeqId = -1;
@@ -6384,27 +6385,6 @@ public class WindowManagerService extends IWindowManager.Stub
}
}
- /**
- * Used by ActivityManager to determine where to position an app with aspect ratio shorter then
- * the screen is.
- * @see DisplayPolicy#getNavBarPosition()
- */
- @Override
- @WindowManagerPolicy.NavigationBarPosition
- public int getNavBarPosition(int displayId) {
- synchronized (mGlobalLock) {
- // Perform layout if it was scheduled before to make sure that we get correct nav bar
- // position when doing rotations.
- final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
- if (displayContent == null) {
- Slog.w(TAG, "getNavBarPosition with invalid displayId=" + displayId
- + " callers=" + Debug.getCallers(3));
- return NAV_BAR_INVALID;
- }
- return displayContent.getDisplayPolicy().getNavBarPosition();
- }
- }
-
@Override
public void createInputConsumer(IBinder token, String name, int displayId,
InputChannel inputChannel) {
@@ -7242,7 +7222,9 @@ public class WindowManagerService extends IWindowManager.Stub
final DisplayContent dc = mRoot.getDisplayContent(displayId);
if (dc != null) {
final DisplayInfo di = dc.getDisplayInfo();
- dc.getDisplayPolicy().getStableInsetsLw(di.rotation, di.displayCutout, outInsets);
+ final WmDisplayCutout cutout = dc.calculateDisplayCutoutForRotation(di.rotation);
+ dc.getDisplayPolicy().getStableInsetsLw(di.rotation, di.logicalWidth, di.logicalHeight,
+ cutout, outInsets);
}
}
diff --git a/services/core/java/com/android/server/wm/WindowOrganizerController.java b/services/core/java/com/android/server/wm/WindowOrganizerController.java
index 68b1d354272d..f83925507512 100644
--- a/services/core/java/com/android/server/wm/WindowOrganizerController.java
+++ b/services/core/java/com/android/server/wm/WindowOrganizerController.java
@@ -1405,7 +1405,7 @@ class WindowOrganizerController extends IWindowOrganizerController.Stub
private BLASTSyncEngine.SyncGroup prepareSyncWithOrganizer(
IWindowContainerTransactionCallback callback) {
final BLASTSyncEngine.SyncGroup s = mService.mWindowManager.mSyncEngine
- .prepareSyncSet(this, "");
+ .prepareSyncSet(this, "", BLASTSyncEngine.METHOD_BLAST);
mTransactionCallbacksByPendingSyncId.put(s.mSyncId, callback);
return s;
}
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index d2b9bda7d742..346930311068 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -242,6 +242,7 @@ import android.view.View;
import android.view.ViewDebug;
import android.view.ViewTreeObserver;
import android.view.WindowInfo;
+import android.view.WindowInsets;
import android.view.WindowInsets.Type.InsetsType;
import android.view.WindowManager;
import android.view.animation.Animation;
@@ -390,7 +391,7 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
*/
int mSyncSeqId = 0;
- /** The last syncId associated with a prepareSync or 0 when no sync is active. */
+ /** The last syncId associated with a BLAST prepareSync or 0 when no BLAST sync is active. */
int mPrepareSyncSeqId = 0;
/**
@@ -1896,6 +1897,19 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
return (mPolicyVisibility & POLICY_VISIBILITY_ALL) == POLICY_VISIBILITY_ALL;
}
+ boolean providesNonDecorInsets() {
+ if (mProvidedInsetsSources == null) {
+ return false;
+ }
+ for (int i = mProvidedInsetsSources.size() - 1; i >= 0; i--) {
+ final int type = mProvidedInsetsSources.keyAt(i);
+ if ((InsetsState.toPublicType(type) & WindowInsets.Type.navigationBars()) != 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
void clearPolicyVisibilityFlag(int policyVisibilityFlag) {
mPolicyVisibility &= ~policyVisibilityFlag;
mWmService.scheduleAnimationLocked();
@@ -2608,14 +2622,19 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
}
removeImmediately();
- // Removing a visible window will effect the computed orientation
- // So just update orientation if needed.
+ boolean sentNewConfig = false;
if (wasVisible) {
+ // Removing a visible window will effect the computed orientation
+ // So just update orientation if needed.
final DisplayContent displayContent = getDisplayContent();
if (displayContent.updateOrientation()) {
displayContent.sendNewConfiguration();
+ sentNewConfig = true;
}
}
+ if (!sentNewConfig && providesNonDecorInsets()) {
+ getDisplayContent().sendNewConfiguration();
+ }
mWmService.updateFocusedWindowLocked(isFocused()
? UPDATE_FOCUS_REMOVING_FOCUS
: UPDATE_FOCUS_NORMAL,
@@ -3892,9 +3911,10 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
fillClientWindowFramesAndConfiguration(mClientWindowFrames, mLastReportedConfiguration,
true /* useLatestConfig */, false /* relayoutVisible */);
final boolean syncRedraw = shouldSendRedrawForSync();
+ final boolean syncWithBuffers = syncRedraw && shouldSyncWithBuffers();
final boolean reportDraw = syncRedraw || drawPending;
final boolean isDragResizeChanged = isDragResizeChanged();
- final boolean forceRelayout = syncRedraw || isDragResizeChanged;
+ final boolean forceRelayout = syncWithBuffers || isDragResizeChanged;
final DisplayContent displayContent = getDisplayContent();
final boolean alwaysConsumeSystemBars =
displayContent.getDisplayPolicy().areSystemBarsForcedShownLw();
@@ -3920,7 +3940,7 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
try {
mClient.resized(mClientWindowFrames, reportDraw, mLastReportedConfiguration,
getCompatInsetsState(), forceRelayout, alwaysConsumeSystemBars, displayId,
- mSyncSeqId, resizeMode);
+ syncWithBuffers ? mSyncSeqId : -1, resizeMode);
if (drawPending && prevRotation >= 0 && prevRotation != mLastReportedConfiguration
.getMergedConfiguration().windowConfiguration.getRotation()) {
mOrientationChangeRedrawRequestTime = SystemClock.elapsedRealtime();
@@ -5924,7 +5944,9 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
}
mSyncSeqId++;
- mPrepareSyncSeqId = mSyncSeqId;
+ if (getSyncMethod() == BLASTSyncEngine.METHOD_BLAST) {
+ mPrepareSyncSeqId = mSyncSeqId;
+ }
requestRedrawForSync();
return true;
}
@@ -5997,6 +6019,7 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
postDrawTransaction = null;
skipLayout = true;
} else if (syncActive) {
+ // Currently in a Sync that is using BLAST.
if (!syncStillPending) {
onSyncFinishedDrawing();
}
@@ -6005,6 +6028,9 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
// Consume the transaction because the sync group will merge it.
postDrawTransaction = null;
}
+ } else if (useBLASTSync()) {
+ // Sync that is not using BLAST
+ onSyncFinishedDrawing();
}
final boolean layoutNeeded =
@@ -6063,6 +6089,18 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP
return useBLASTSync();
}
+ int getSyncMethod() {
+ final BLASTSyncEngine.SyncGroup syncGroup = getSyncGroup();
+ if (syncGroup == null) return BLASTSyncEngine.METHOD_NONE;
+ if (mSyncMethodOverride != BLASTSyncEngine.METHOD_UNDEFINED) return mSyncMethodOverride;
+ return syncGroup.mSyncMethod;
+ }
+
+ boolean shouldSyncWithBuffers() {
+ if (!mDrawHandlers.isEmpty()) return true;
+ return getSyncMethod() == BLASTSyncEngine.METHOD_BLAST;
+ }
+
void requestRedrawForSync() {
mRedrawForSyncReported = false;
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java
index 054181dfa728..0305c35b1828 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java
@@ -671,6 +671,21 @@ class DevicePolicyData {
if (mFactoryResetReason != null) {
pw.print("mFactoryResetReason="); pw.println(mFactoryResetReason);
}
+ if (mDelegationMap.size() != 0) {
+ pw.println("mDelegationMap=");
+ pw.increaseIndent();
+ for (int i = 0; i < mDelegationMap.size(); i++) {
+ List<String> delegationScopes = mDelegationMap.valueAt(i);
+ pw.println(mDelegationMap.keyAt(i) + "[size=" + delegationScopes.size()
+ + "]");
+ pw.increaseIndent();
+ for (int j = 0; j < delegationScopes.size(); j++) {
+ pw.println(j + ": " + delegationScopes.get(j));
+ }
+ pw.decreaseIndent();
+ }
+ pw.decreaseIndent();
+ }
pw.decreaseIndent();
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 0018a523a34a..fbaf1ce25b85 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -5786,29 +5786,8 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
@VisibleForTesting
public void enforceCallerCanRequestDeviceIdAttestation(CallerIdentity caller)
throws SecurityException {
- /**
- * First check if there's a profile owner because the device could be in COMP mode (where
- * there's a device owner and profile owner on the same device).
- * If the caller is from the work profile, then it must be the PO or the delegate, and
- * it must have the right permission to access device identifiers.
- */
- int callerUserId = caller.getUserId();
- if (hasProfileOwner(callerUserId)) {
- // Make sure that the caller is the profile owner or delegate.
- Preconditions.checkCallAuthorization(canInstallCertificates(caller));
- // Verify that the managed profile is on an organization-owned device (or is affiliated
- // with the device owner user) and as such the profile owner can access Device IDs.
- if (isProfileOwnerOfOrganizationOwnedDevice(callerUserId)
- || isUserAffiliatedWithDevice(callerUserId)) {
- return;
- }
- throw new SecurityException(
- "Profile Owner is not allowed to access Device IDs.");
- }
-
- // If not, fall back to the device owner check.
- Preconditions.checkCallAuthorization(
- isDefaultDeviceOwner(caller) || isCallerDelegate(caller, DELEGATION_CERT_INSTALL));
+ Preconditions.checkCallAuthorization(hasDeviceIdAccessUnchecked(caller.getPackageName(),
+ caller.getUid()));
}
@VisibleForTesting
@@ -5856,7 +5835,6 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
final boolean deviceIdAttestationRequired = attestationUtilsFlags != null;
KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
final String alias = keySpec.getKeystoreAlias();
-
Preconditions.checkStringNotEmpty(alias, "Empty alias provided");
Preconditions.checkArgument(
!deviceIdAttestationRequired || keySpec.getAttestationChallenge() != null,
@@ -8166,7 +8144,8 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
}
final CallerIdentity caller = getCallerIdentity(who);
- Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
+ Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)
+ || isCameraServerUid(caller));
if (parent) {
Preconditions.checkCallAuthorization(
@@ -9393,26 +9372,33 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
if (!hasPermission(permission.READ_PHONE_STATE, pid, uid)) {
return false;
}
+ return hasDeviceIdAccessUnchecked(packageName, uid);
+ }
- // Allow access to the device owner or delegate cert installer or profile owner of an
- // affiliated user
+ /**
+ * Check if caller is device owner, delegate cert installer or profile owner of
+ * affiliated user. Or if caller is profile owner for a specified user or delegate cert
+ * installer on an organization-owned device.
+ */
+ private boolean hasDeviceIdAccessUnchecked(String packageName, int uid) {
+ // Is the caller a device owner, delegate cert installer or profile owner of an
+ // affiliated user.
ComponentName deviceOwner = getDeviceOwnerComponent(true);
if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName)
|| isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) {
return true;
}
final int userId = UserHandle.getUserId(uid);
- // Allow access to the profile owner for the specified user, or delegate cert installer
- // But only if this is an organization-owned device.
+ // Is the caller the profile owner for the specified user, or delegate cert installer on an
+ // organization-owned device.
ComponentName profileOwner = getProfileOwnerAsUser(userId);
final boolean isCallerProfileOwnerOrDelegate = profileOwner != null
&& (profileOwner.getPackageName().equals(packageName)
- || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL));
+ || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL));
if (isCallerProfileOwnerOrDelegate && (isProfileOwnerOfOrganizationOwnedDevice(userId)
|| isUserAffiliatedWithDevice(userId))) {
return true;
}
-
return false;
}
@@ -9681,6 +9667,10 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
return UserHandle.isSameApp(caller.getUid(), Process.SHELL_UID);
}
+ private boolean isCameraServerUid(CallerIdentity caller) {
+ return UserHandle.isSameApp(caller.getUid(), Process.CAMERASERVER_UID);
+ }
+
private @UserIdInt int getCurrentForegroundUserId() {
try {
UserInfo currentUser = mInjector.getIActivityManager().getCurrentUser();
diff --git a/services/tests/mockingservicestests/src/com/android/server/job/controllers/BatteryControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/job/controllers/BatteryControllerTest.java
index 4a631a1251d5..59cb43f16ef6 100644
--- a/services/tests/mockingservicestests/src/com/android/server/job/controllers/BatteryControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/job/controllers/BatteryControllerTest.java
@@ -33,6 +33,7 @@ import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
+import android.content.pm.PackageManager;
import android.content.pm.PackageManagerInternal;
import android.os.BatteryManagerInternal;
import android.os.RemoteException;
@@ -75,6 +76,8 @@ public class BatteryControllerTest {
private JobSchedulerService mJobSchedulerService;
@Mock
private PackageManagerInternal mPackageManagerInternal;
+ @Mock
+ private PackageManager mPackageManager;
@Before
public void setUp() {
@@ -100,6 +103,9 @@ public class BatteryControllerTest {
ArgumentCaptor<BroadcastReceiver> receiverCaptor =
ArgumentCaptor.forClass(BroadcastReceiver.class);
+ when(mContext.getPackageManager()).thenReturn(mPackageManager);
+ when(mPackageManager.hasSystemFeature(
+ PackageManager.FEATURE_AUTOMOTIVE)).thenReturn(false);
mFlexibilityController =
new FlexibilityController(mJobSchedulerService, mock(PrefetchController.class));
mBatteryController = new BatteryController(mJobSchedulerService, mFlexibilityController);
diff --git a/services/tests/mockingservicestests/src/com/android/server/job/controllers/ConnectivityControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/job/controllers/ConnectivityControllerTest.java
index 953a72d5085c..1f85f2c2c46e 100644
--- a/services/tests/mockingservicestests/src/com/android/server/job/controllers/ConnectivityControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/job/controllers/ConnectivityControllerTest.java
@@ -51,6 +51,7 @@ import android.annotation.Nullable;
import android.app.job.JobInfo;
import android.content.ComponentName;
import android.content.Context;
+import android.content.pm.PackageManager;
import android.content.pm.PackageManagerInternal;
import android.net.ConnectivityManager;
import android.net.ConnectivityManager.NetworkCallback;
@@ -96,6 +97,8 @@ public class ConnectivityControllerTest {
private NetworkPolicyManagerInternal mNetPolicyManagerInternal;
@Mock
private JobSchedulerService mService;
+ @Mock
+ private PackageManager mPackageManager;
private Constants mConstants;
@@ -115,10 +118,6 @@ public class ConnectivityControllerTest {
LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);
LocalServices.addService(NetworkPolicyManagerInternal.class, mNetPolicyManagerInternal);
- when(mContext.getMainLooper()).thenReturn(Looper.getMainLooper());
- mFlexibilityController =
- new FlexibilityController(mService, mock(PrefetchController.class));
-
// Freeze the clocks at this moment in time
JobSchedulerService.sSystemClock =
Clock.fixed(Clock.systemUTC().instant(), ZoneOffset.UTC);
@@ -142,6 +141,13 @@ public class ConnectivityControllerTest {
when(mService.getTestableContext()).thenReturn(mContext);
when(mService.getLock()).thenReturn(mService);
when(mService.getConstants()).thenReturn(mConstants);
+ // Instantiate Flexibility Controller
+ when(mContext.getMainLooper()).thenReturn(Looper.getMainLooper());
+ when(mContext.getPackageManager()).thenReturn(mPackageManager);
+ when(mPackageManager.hasSystemFeature(
+ PackageManager.FEATURE_AUTOMOTIVE)).thenReturn(false);
+ mFlexibilityController =
+ new FlexibilityController(mService, mock(PrefetchController.class));
}
@Test
diff --git a/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java
index 9d039bd09a2f..0eb0a002fe6e 100644
--- a/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java
@@ -29,10 +29,12 @@ import static com.android.server.job.controllers.FlexibilityController.FcConfig.
import static com.android.server.job.controllers.FlexibilityController.FcConfig.KEY_FALLBACK_FLEXIBILITY_DEADLINE;
import static com.android.server.job.controllers.FlexibilityController.FcConfig.KEY_FLEXIBILITY_ENABLED;
import static com.android.server.job.controllers.FlexibilityController.FcConfig.KEY_PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS;
+import static com.android.server.job.controllers.FlexibilityController.NUM_FLEXIBLE_CONSTRAINTS;
import static com.android.server.job.controllers.JobStatus.CONSTRAINT_BATTERY_NOT_LOW;
import static com.android.server.job.controllers.JobStatus.CONSTRAINT_CHARGING;
import static com.android.server.job.controllers.JobStatus.CONSTRAINT_FLEXIBLE;
import static com.android.server.job.controllers.JobStatus.CONSTRAINT_IDLE;
+import static com.android.server.job.controllers.JobStatus.NO_LATEST_RUNTIME;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@@ -48,6 +50,7 @@ import android.app.AlarmManager;
import android.app.job.JobInfo;
import android.content.ComponentName;
import android.content.Context;
+import android.content.pm.PackageManager;
import android.content.pm.PackageManagerInternal;
import android.os.Looper;
import android.provider.DeviceConfig;
@@ -90,6 +93,8 @@ public class FlexibilityControllerTest {
private JobSchedulerService mJobSchedulerService;
@Mock
private PrefetchController mPrefetchController;
+ @Mock
+ private PackageManager mPackageManager;
@Before
public void setup() {
@@ -107,6 +112,9 @@ public class FlexibilityControllerTest {
// Called in FlexibilityController constructor.
when(mContext.getMainLooper()).thenReturn(Looper.getMainLooper());
when(mContext.getSystemService(Context.ALARM_SERVICE)).thenReturn(mAlarmManager);
+ when(mContext.getPackageManager()).thenReturn(mPackageManager);
+ when(mPackageManager.hasSystemFeature(
+ PackageManager.FEATURE_AUTOMOTIVE)).thenReturn(false);
// Used in FlexibilityController.FcConstants.
doAnswer((Answer<Void>) invocationOnMock -> null)
.when(() -> DeviceConfig.addOnPropertiesChangedListener(
@@ -190,7 +198,7 @@ public class FlexibilityControllerTest {
*/
@Test
public void testDefaultVariableValues() {
- assertEquals(FlexibilityController.NUM_FLEXIBLE_CONSTRAINTS,
+ assertEquals(NUM_FLEXIBLE_CONSTRAINTS,
mFlexibilityController.mFcConfig.DEFAULT_PERCENT_TO_DROP_FLEXIBLE_CONSTRAINTS.length
);
}
@@ -390,7 +398,7 @@ public class FlexibilityControllerTest {
}
@Test
- public void testGetLifeCycleBeginningElapsedLocked_prefetch() {
+ public void testGetLifeCycleBeginningElapsedLocked_Prefetch() {
// prefetch with lifecycle
when(mPrefetchController.getLaunchTimeThresholdMs()).thenReturn(700L);
JobInfo.Builder jb = createJob(0).setPrefetch(true);
@@ -417,7 +425,7 @@ public class FlexibilityControllerTest {
}
@Test
- public void testGetLifeCycleBeginningElapsedLocked_nonPrefetch() {
+ public void testGetLifeCycleBeginningElapsedLocked_NonPrefetch() {
// delay
long delay = 100;
JobInfo.Builder jb = createJob(0).setMinimumLatency(delay);
@@ -432,7 +440,7 @@ public class FlexibilityControllerTest {
}
@Test
- public void testGetLifeCycleEndElapsedLocked_prefetch() {
+ public void testGetLifeCycleEndElapsedLocked_Prefetch() {
// prefetch no estimate
JobInfo.Builder jb = createJob(0).setPrefetch(true);
JobStatus js = createJobStatus("time", jb);
@@ -444,8 +452,9 @@ public class FlexibilityControllerTest {
when(mPrefetchController.getNextEstimatedLaunchTimeLocked(js)).thenReturn(1000L);
assertEquals(1000L, mFlexibilityController.getLifeCycleEndElapsedLocked(js, 0));
}
+
@Test
- public void testGetLifeCycleEndElapsedLocked_nonPrefetch() {
+ public void testGetLifeCycleEndElapsedLocked_NonPrefetch() {
// deadline
JobInfo.Builder jb = createJob(0).setOverrideDeadline(1000L);
JobStatus js = createJobStatus("time", jb);
@@ -459,6 +468,28 @@ public class FlexibilityControllerTest {
}
@Test
+ public void testGetLifeCycleEndElapsedLocked_Rescheduled() {
+ JobInfo.Builder jb = createJob(0).setOverrideDeadline(1000L);
+ JobStatus js = createJobStatus("time", jb);
+ js = new JobStatus(
+ js, FROZEN_TIME, NO_LATEST_RUNTIME, /* numFailures */ 2, FROZEN_TIME, FROZEN_TIME);
+
+ assertEquals(mFcConfig.RESCHEDULED_JOB_DEADLINE_MS,
+ mFlexibilityController.getLifeCycleEndElapsedLocked(js, 0));
+
+ js = new JobStatus(
+ js, FROZEN_TIME, NO_LATEST_RUNTIME, /* numFailures */ 3, FROZEN_TIME, FROZEN_TIME);
+
+ assertEquals(2 * mFcConfig.RESCHEDULED_JOB_DEADLINE_MS,
+ mFlexibilityController.getLifeCycleEndElapsedLocked(js, 0));
+
+ js = new JobStatus(
+ js, FROZEN_TIME, NO_LATEST_RUNTIME, /* numFailures */ 10, FROZEN_TIME, FROZEN_TIME);
+ assertEquals(mFcConfig.MAX_RESCHEDULED_DEADLINE_MS,
+ mFlexibilityController.getLifeCycleEndElapsedLocked(js, 0));
+ }
+
+ @Test
public void testWontStopJobFromRunning() {
JobStatus js = createJobStatus("testWontStopJobFromRunning", createJob(101));
// Stop satisfied constraints from causing a false positive.
@@ -473,9 +504,9 @@ public class FlexibilityControllerTest {
public void testFlexibilityTracker() {
FlexibilityController.FlexibilityTracker flexTracker =
mFlexibilityController.new
- FlexibilityTracker(FlexibilityController.NUM_FLEXIBLE_CONSTRAINTS);
-
- assertEquals(4, flexTracker.size());
+ FlexibilityTracker(NUM_FLEXIBLE_CONSTRAINTS);
+ // Plus one for jobs with 0 required constraint.
+ assertEquals(NUM_FLEXIBLE_CONSTRAINTS + 1, flexTracker.size());
JobStatus[] jobs = new JobStatus[4];
JobInfo.Builder jb;
for (int i = 0; i < jobs.length; i++) {
@@ -495,47 +526,53 @@ public class FlexibilityControllerTest {
synchronized (mFlexibilityController.mLock) {
ArrayList<ArraySet<JobStatus>> trackedJobs = flexTracker.getArrayList();
- assertEquals(0, trackedJobs.get(0).size());
+ assertEquals(1, trackedJobs.get(0).size());
assertEquals(0, trackedJobs.get(1).size());
- assertEquals(3, trackedJobs.get(2).size());
- assertEquals(0, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(2).size());
+ assertEquals(3, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(4).size());
flexTracker.adjustJobsRequiredConstraints(jobs[0], -1, FROZEN_TIME);
- assertEquals(0, trackedJobs.get(0).size());
- assertEquals(1, trackedJobs.get(1).size());
- assertEquals(2, trackedJobs.get(2).size());
- assertEquals(0, trackedJobs.get(3).size());
+ assertEquals(1, trackedJobs.get(0).size());
+ assertEquals(0, trackedJobs.get(1).size());
+ assertEquals(1, trackedJobs.get(2).size());
+ assertEquals(2, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(4).size());
flexTracker.adjustJobsRequiredConstraints(jobs[0], -1, FROZEN_TIME);
assertEquals(1, trackedJobs.get(0).size());
- assertEquals(0, trackedJobs.get(1).size());
- assertEquals(2, trackedJobs.get(2).size());
- assertEquals(0, trackedJobs.get(3).size());
+ assertEquals(1, trackedJobs.get(1).size());
+ assertEquals(0, trackedJobs.get(2).size());
+ assertEquals(2, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(4).size());
flexTracker.adjustJobsRequiredConstraints(jobs[0], -1, FROZEN_TIME);
- assertEquals(0, trackedJobs.get(0).size());
+ assertEquals(2, trackedJobs.get(0).size());
assertEquals(0, trackedJobs.get(1).size());
- assertEquals(2, trackedJobs.get(2).size());
- assertEquals(0, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(2).size());
+ assertEquals(2, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(4).size());
flexTracker.remove(jobs[1]);
- assertEquals(0, trackedJobs.get(0).size());
+ assertEquals(2, trackedJobs.get(0).size());
assertEquals(0, trackedJobs.get(1).size());
- assertEquals(1, trackedJobs.get(2).size());
- assertEquals(0, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(2).size());
+ assertEquals(1, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(4).size());
flexTracker.resetJobNumDroppedConstraints(jobs[0], FROZEN_TIME);
- assertEquals(0, trackedJobs.get(0).size());
+ assertEquals(2, trackedJobs.get(0).size());
assertEquals(0, trackedJobs.get(1).size());
- assertEquals(2, trackedJobs.get(2).size());
- assertEquals(0, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(2).size());
+ assertEquals(2, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(4).size());
flexTracker.adjustJobsRequiredConstraints(jobs[0], -2, FROZEN_TIME);
-
- assertEquals(1, trackedJobs.get(0).size());
- assertEquals(0, trackedJobs.get(1).size());
- assertEquals(1, trackedJobs.get(2).size());
- assertEquals(0, trackedJobs.get(3).size());
+ assertEquals(2, trackedJobs.get(0).size());
+ assertEquals(1, trackedJobs.get(1).size());
+ assertEquals(0, trackedJobs.get(2).size());
+ assertEquals(1, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(4).size());
final long nowElapsed = ((DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_MS / 2)
+ HOUR_IN_MILLIS);
@@ -543,10 +580,11 @@ public class FlexibilityControllerTest {
Clock.fixed(Instant.ofEpochMilli(nowElapsed), ZoneOffset.UTC);
flexTracker.resetJobNumDroppedConstraints(jobs[0], nowElapsed);
- assertEquals(0, trackedJobs.get(0).size());
- assertEquals(1, trackedJobs.get(1).size());
+ assertEquals(2, trackedJobs.get(0).size());
+ assertEquals(0, trackedJobs.get(1).size());
assertEquals(1, trackedJobs.get(2).size());
- assertEquals(0, trackedJobs.get(3).size());
+ assertEquals(1, trackedJobs.get(3).size());
+ assertEquals(0, trackedJobs.get(4).size());
}
}
@@ -578,6 +616,15 @@ public class FlexibilityControllerTest {
}
@Test
+ public void testExceptions_RescheduledOnce() {
+ JobInfo.Builder jb = createJob(0);
+ JobStatus js = createJobStatus("time", jb);
+ js = new JobStatus(
+ js, FROZEN_TIME, NO_LATEST_RUNTIME, /* numFailures */ 1, FROZEN_TIME, FROZEN_TIME);
+ assertFalse(js.hasFlexibilityConstraint());
+ }
+
+ @Test
public void testExceptions_None() {
JobInfo.Builder jb = createJob(0);
JobStatus js = createJobStatus("testExceptions_None", jb);
@@ -818,6 +865,29 @@ public class FlexibilityControllerTest {
}
+ @Test
+ public void testDeviceDisabledFlexibility_Auto() {
+ when(mPackageManager.hasSystemFeature(
+ PackageManager.FEATURE_AUTOMOTIVE)).thenReturn(true);
+ mFlexibilityController =
+ new FlexibilityController(mJobSchedulerService, mPrefetchController);
+ assertFalse(mFlexibilityController.mFlexibilityEnabled);
+
+ JobStatus js = createJobStatus("testIsAuto", createJob(0));
+
+ mFlexibilityController.maybeStartTrackingJobLocked(js, null);
+ assertTrue(js.isConstraintSatisfied(CONSTRAINT_FLEXIBLE));
+
+ setDeviceConfigBoolean(KEY_FLEXIBILITY_ENABLED, true);
+ assertFalse(mFlexibilityController.mFlexibilityEnabled);
+
+ ArrayList<ArraySet<JobStatus>> jobs =
+ mFlexibilityController.mFlexibilityTracker.getArrayList();
+ for (int i = 0; i < jobs.size(); i++) {
+ assertEquals(0, jobs.get(i).size());
+ }
+ }
+
private void setUidBias(int uid, int bias) {
int prevBias = mJobSchedulerService.getUidBias(uid);
doReturn(bias).when(mJobSchedulerService).getUidBias(uid);
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/BiometricStateCallbackTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/BiometricStateCallbackTest.java
index 0e30782eaece..3b66eaba6129 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/BiometricStateCallbackTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/BiometricStateCallbackTest.java
@@ -80,6 +80,8 @@ public class BiometricStateCallbackTest {
when(mFakeProvider.hasEnrollments(eq(SENSOR_ID), eq(USER_ID))).thenReturn(true);
when(mUserManager.getAliveUsers()).thenReturn(
List.of(new UserInfo(USER_ID, "name", 0)));
+ when(mBiometricStateListener.asBinder()).thenReturn(mBiometricStateListener);
+
mCallback = new BiometricStateCallback<>(mUserManager);
mCallback.registerBiometricStateListener(mBiometricStateListener);
@@ -110,6 +112,14 @@ public class BiometricStateCallbackTest {
false /* expectCallback */, false /* expectedCallbackValue */);
}
+ @Test
+ public void testBinderDeath() {
+ mCallback.binderDied(mBiometricStateListener.asBinder());
+
+ testEnrollmentCallback(true /* changed */, false /* isNowEnrolled */,
+ false /* expectCallback */, false /* expectedCallbackValue */);
+ }
+
private void testEnrollmentCallback(boolean changed, boolean isNowEnrolled,
boolean expectCallback, boolean expectedCallbackValue) {
EnrollClient<?> client = mock(EnrollClient.class);
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
index d62ac99e530b..598a22bbde39 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
@@ -93,7 +93,6 @@ import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
-import android.os.Parcel;
import android.os.RemoteCallback;
import android.os.RemoteException;
import android.os.UserHandle;
@@ -2448,35 +2447,6 @@ public class PreferencesHelperTest extends UiServiceTestCase {
}
@Test
- public void testGetNotificationChannelGroup() throws Exception {
- NotificationChannelGroup notDeleted = new NotificationChannelGroup("not", "deleted");
- NotificationChannel base =
- new NotificationChannel("not deleted", "belongs to notDeleted", IMPORTANCE_DEFAULT);
- base.setGroup("not");
- NotificationChannel convo =
- new NotificationChannel("convo", "belongs to notDeleted", IMPORTANCE_DEFAULT);
- convo.setGroup("not");
- convo.setConversationId("not deleted", "banana");
-
- mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, notDeleted, true);
- mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, base, true, false);
- mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, convo, true, false);
- mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, notDeleted, true);
-
- NotificationChannelGroup g
- = mHelper.getNotificationChannelGroup(notDeleted.getId(), PKG_N_MR1, UID_N_MR1);
- Parcel parcel = Parcel.obtain();
- g.writeToParcel(parcel, 0);
- parcel.setDataPosition(0);
-
- NotificationChannelGroup g2
- = mHelper.getNotificationChannelGroup(notDeleted.getId(), PKG_N_MR1, UID_N_MR1);
- Parcel parcel2 = Parcel.obtain();
- g2.writeToParcel(parcel2, 0);
- parcel2.setDataPosition(0);
- }
-
- @Test
public void testOnUserRemoved() throws Exception {
int[] user0Uids = {98, 235, 16, 3782};
int[] user1Uids = new int[user0Uids.length];
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index 15d1a3c48ccd..44494831eb68 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -158,6 +158,7 @@ import androidx.test.filters.MediumTest;
import com.android.internal.R;
import com.android.server.wm.ActivityRecord.State;
+import com.android.server.wm.utils.WmDisplayCutout;
import org.junit.Assert;
import org.junit.Before;
@@ -551,7 +552,8 @@ public class ActivityRecordTests extends WindowTestsBase {
final Rect insets = new Rect();
final DisplayInfo displayInfo = task.mDisplayContent.getDisplayInfo();
final DisplayPolicy policy = task.mDisplayContent.getDisplayPolicy();
- policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.displayCutout, insets);
+ policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.logicalWidth,
+ displayInfo.logicalHeight, WmDisplayCutout.NO_CUTOUT, insets);
policy.convertNonDecorInsetsToStableInsets(insets, displayInfo.rotation);
Task.intersectWithInsetsIfFits(stableRect, stableRect, insets);
@@ -592,7 +594,8 @@ public class ActivityRecordTests extends WindowTestsBase {
final Rect insets = new Rect();
final DisplayInfo displayInfo = rootTask.mDisplayContent.getDisplayInfo();
final DisplayPolicy policy = rootTask.mDisplayContent.getDisplayPolicy();
- policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.displayCutout, insets);
+ policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.logicalWidth,
+ displayInfo.logicalHeight, WmDisplayCutout.NO_CUTOUT, insets);
policy.convertNonDecorInsetsToStableInsets(insets, displayInfo.rotation);
Task.intersectWithInsetsIfFits(stableRect, stableRect, insets);
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyInsetsTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyInsetsTests.java
index 2158cafbb64a..aa5a74e962e6 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyInsetsTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyInsetsTests.java
@@ -25,10 +25,13 @@ import static org.hamcrest.Matchers.equalTo;
import android.graphics.Rect;
import android.platform.test.annotations.Presubmit;
+import android.util.Pair;
import android.view.DisplayInfo;
import androidx.test.filters.SmallTest;
+import com.android.server.wm.utils.WmDisplayCutout;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
@@ -46,7 +49,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase {
@Test
public void portrait() {
- final DisplayInfo di = displayInfoForRotation(ROTATION_0, false /* withCutout */);
+ final Pair<DisplayInfo, WmDisplayCutout> di =
+ displayInfoForRotation(ROTATION_0, false /* withCutout */);
verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT);
verifyNonDecorInsets(di, 0, 0, 0, NAV_BAR_HEIGHT);
@@ -55,7 +59,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase {
@Test
public void portrait_withCutout() {
- final DisplayInfo di = displayInfoForRotation(ROTATION_0, true /* withCutout */);
+ final Pair<DisplayInfo, WmDisplayCutout> di =
+ displayInfoForRotation(ROTATION_0, true /* withCutout */);
verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT);
verifyNonDecorInsets(di, 0, DISPLAY_CUTOUT_HEIGHT, 0, NAV_BAR_HEIGHT);
@@ -64,7 +69,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase {
@Test
public void landscape() {
- final DisplayInfo di = displayInfoForRotation(ROTATION_90, false /* withCutout */);
+ final Pair<DisplayInfo, WmDisplayCutout> di =
+ displayInfoForRotation(ROTATION_90, false /* withCutout */);
if (mDisplayPolicy.navigationBarCanMove()) {
verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
@@ -79,7 +85,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase {
@Test
public void landscape_withCutout() {
- final DisplayInfo di = displayInfoForRotation(ROTATION_90, true /* withCutout */);
+ final Pair<DisplayInfo, WmDisplayCutout> di =
+ displayInfoForRotation(ROTATION_90, true /* withCutout */);
if (mDisplayPolicy.navigationBarCanMove()) {
verifyStableInsets(di, DISPLAY_CUTOUT_HEIGHT, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
@@ -94,7 +101,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase {
@Test
public void seascape() {
- final DisplayInfo di = displayInfoForRotation(ROTATION_270, false /* withCutout */);
+ final Pair<DisplayInfo, WmDisplayCutout> di =
+ displayInfoForRotation(ROTATION_270, false /* withCutout */);
if (mDisplayPolicy.navigationBarCanMove()) {
verifyStableInsets(di, NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, 0, 0);
@@ -109,7 +117,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase {
@Test
public void seascape_withCutout() {
- final DisplayInfo di = displayInfoForRotation(ROTATION_270, true /* withCutout */);
+ final Pair<DisplayInfo, WmDisplayCutout> di =
+ displayInfoForRotation(ROTATION_270, true /* withCutout */);
if (mDisplayPolicy.navigationBarCanMove()) {
verifyStableInsets(di, NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, DISPLAY_CUTOUT_HEIGHT, 0);
@@ -124,7 +133,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase {
@Test
public void upsideDown() {
- final DisplayInfo di = displayInfoForRotation(ROTATION_180, false /* withCutout */);
+ final Pair<DisplayInfo, WmDisplayCutout> di =
+ displayInfoForRotation(ROTATION_180, false /* withCutout */);
verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT);
verifyNonDecorInsets(di, 0, 0, 0, NAV_BAR_HEIGHT);
@@ -133,28 +143,34 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase {
@Test
public void upsideDown_withCutout() {
- final DisplayInfo di = displayInfoForRotation(ROTATION_180, true /* withCutout */);
+ final Pair<DisplayInfo, WmDisplayCutout> di =
+ displayInfoForRotation(ROTATION_180, true /* withCutout */);
verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT + DISPLAY_CUTOUT_HEIGHT);
verifyNonDecorInsets(di, 0, 0, 0, NAV_BAR_HEIGHT + DISPLAY_CUTOUT_HEIGHT);
verifyConsistency(di);
}
- private void verifyStableInsets(DisplayInfo di, int left, int top, int right, int bottom) {
- mErrorCollector.checkThat("stableInsets", getStableInsetsLw(di), equalTo(new Rect(
- left, top, right, bottom)));
+ private void verifyStableInsets(Pair<DisplayInfo, WmDisplayCutout> diPair, int left, int top,
+ int right, int bottom) {
+ mErrorCollector.checkThat("stableInsets", getStableInsetsLw(diPair.first, diPair.second),
+ equalTo(new Rect(left, top, right, bottom)));
}
- private void verifyNonDecorInsets(DisplayInfo di, int left, int top, int right, int bottom) {
- mErrorCollector.checkThat("nonDecorInsets", getNonDecorInsetsLw(di), equalTo(new Rect(
+ private void verifyNonDecorInsets(Pair<DisplayInfo, WmDisplayCutout> diPair, int left, int top,
+ int right, int bottom) {
+ mErrorCollector.checkThat("nonDecorInsets",
+ getNonDecorInsetsLw(diPair.first, diPair.second), equalTo(new Rect(
left, top, right, bottom)));
}
- private void verifyConsistency(DisplayInfo di) {
- verifyConsistency("configDisplay", di, getStableInsetsLw(di),
- getConfigDisplayWidth(di), getConfigDisplayHeight(di));
- verifyConsistency("nonDecorDisplay", di, getNonDecorInsetsLw(di),
- getNonDecorDisplayWidth(di), getNonDecorDisplayHeight(di));
+ private void verifyConsistency(Pair<DisplayInfo, WmDisplayCutout> diPair) {
+ final DisplayInfo di = diPair.first;
+ final WmDisplayCutout cutout = diPair.second;
+ verifyConsistency("configDisplay", di, getStableInsetsLw(di, cutout),
+ getConfigDisplayWidth(di, cutout), getConfigDisplayHeight(di, cutout));
+ verifyConsistency("nonDecorDisplay", di, getNonDecorInsetsLw(di, cutout),
+ getNonDecorDisplayWidth(di, cutout), getNonDecorDisplayHeight(di, cutout));
}
private void verifyConsistency(String what, DisplayInfo di, Rect insets, int width,
@@ -165,39 +181,42 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase {
equalTo(di.logicalHeight - insets.top - insets.bottom));
}
- private Rect getStableInsetsLw(DisplayInfo di) {
+ private Rect getStableInsetsLw(DisplayInfo di, WmDisplayCutout cutout) {
Rect result = new Rect();
- mDisplayPolicy.getStableInsetsLw(di.rotation, di.displayCutout, result);
+ mDisplayPolicy.getStableInsetsLw(di.rotation, di.logicalWidth, di.logicalHeight,
+ cutout, result);
return result;
}
- private Rect getNonDecorInsetsLw(DisplayInfo di) {
+ private Rect getNonDecorInsetsLw(DisplayInfo di, WmDisplayCutout cutout) {
Rect result = new Rect();
- mDisplayPolicy.getNonDecorInsetsLw(di.rotation, di.displayCutout, result);
+ mDisplayPolicy.getNonDecorInsetsLw(di.rotation, di.logicalWidth, di.logicalHeight,
+ cutout, result);
return result;
}
- private int getNonDecorDisplayWidth(DisplayInfo di) {
- return mDisplayPolicy.getNonDecorDisplayWidth(di.logicalWidth, di.logicalHeight,
- di.rotation, 0 /* ui */, di.displayCutout);
+ private int getNonDecorDisplayWidth(DisplayInfo di, WmDisplayCutout cutout) {
+ return mDisplayPolicy.getNonDecorDisplayFrame(di.logicalWidth, di.logicalHeight,
+ di.rotation, cutout).width();
}
- private int getNonDecorDisplayHeight(DisplayInfo di) {
- return mDisplayPolicy.getNonDecorDisplayHeight(di.logicalHeight, di.rotation,
- di.displayCutout);
+ private int getNonDecorDisplayHeight(DisplayInfo di, WmDisplayCutout cutout) {
+ return mDisplayPolicy.getNonDecorDisplayFrame(di.logicalWidth, di.logicalHeight,
+ di.rotation, cutout).height();
}
- private int getConfigDisplayWidth(DisplayInfo di) {
- return mDisplayPolicy.getConfigDisplayWidth(di.logicalWidth, di.logicalHeight,
- di.rotation, 0 /* ui */, di.displayCutout);
+ private int getConfigDisplayWidth(DisplayInfo di, WmDisplayCutout cutout) {
+ return mDisplayPolicy.getConfigDisplaySize(di.logicalWidth, di.logicalHeight,
+ di.rotation, cutout).x;
}
- private int getConfigDisplayHeight(DisplayInfo di) {
- return mDisplayPolicy.getConfigDisplayHeight(di.logicalWidth, di.logicalHeight,
- di.rotation, 0 /* ui */, di.displayCutout);
+ private int getConfigDisplayHeight(DisplayInfo di, WmDisplayCutout cutout) {
+ return mDisplayPolicy.getConfigDisplaySize(di.logicalWidth, di.logicalHeight,
+ di.rotation, cutout).y;
}
- private static DisplayInfo displayInfoForRotation(int rotation, boolean withDisplayCutout) {
- return displayInfoAndCutoutForRotation(rotation, withDisplayCutout, false).first;
+ private static Pair<DisplayInfo, WmDisplayCutout> displayInfoForRotation(int rotation,
+ boolean withDisplayCutout) {
+ return displayInfoAndCutoutForRotation(rotation, withDisplayCutout, false);
}
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/SyncEngineTests.java b/services/tests/wmtests/src/com/android/server/wm/SyncEngineTests.java
index 420ea8e63562..d3aa073c84d8 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SyncEngineTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SyncEngineTests.java
@@ -16,13 +16,18 @@
package com.android.server.wm;
+import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
+
import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.times;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
+import static com.android.server.wm.BLASTSyncEngine.METHOD_BLAST;
+import static com.android.server.wm.BLASTSyncEngine.METHOD_NONE;
import static com.android.server.wm.WindowContainer.POSITION_BOTTOM;
import static com.android.server.wm.WindowContainer.POSITION_TOP;
import static com.android.server.wm.WindowContainer.SYNC_STATE_NONE;
+import static com.android.server.wm.WindowState.BLAST_TIMEOUT_DURATION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -67,7 +72,7 @@ public class SyncEngineTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener listener = mock(
BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(listener);
+ int id = startSyncSet(bse, listener);
bse.addToSyncSet(id, mockWC);
// Make sure a traversal is requested
verify(mWm.mWindowPlacerLocked, times(1)).requestTraversal();
@@ -95,7 +100,7 @@ public class SyncEngineTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener listener = mock(
BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(listener);
+ int id = startSyncSet(bse, listener);
bse.addToSyncSet(id, mockWC);
bse.setReady(id);
// Make sure traversals requested (one for add and another for setReady)
@@ -119,7 +124,7 @@ public class SyncEngineTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener listener = mock(
BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(listener);
+ int id = startSyncSet(bse, listener);
bse.addToSyncSet(id, mockWC);
bse.setReady(id);
// Make sure traversals requested (one for add and another for setReady)
@@ -147,7 +152,7 @@ public class SyncEngineTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener listener = mock(
BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(listener);
+ int id = startSyncSet(bse, listener);
bse.addToSyncSet(id, parentWC);
bse.setReady(id);
bse.onSurfacePlacement();
@@ -180,7 +185,7 @@ public class SyncEngineTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener listener = mock(
BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(listener);
+ int id = startSyncSet(bse, listener);
bse.addToSyncSet(id, parentWC);
bse.setReady(id);
bse.onSurfacePlacement();
@@ -211,7 +216,7 @@ public class SyncEngineTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener listener = mock(
BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(listener);
+ int id = startSyncSet(bse, listener);
bse.addToSyncSet(id, parentWC);
bse.setReady(id);
bse.onSurfacePlacement();
@@ -243,7 +248,7 @@ public class SyncEngineTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener listener = mock(
BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(listener);
+ int id = startSyncSet(bse, listener);
bse.addToSyncSet(id, parentWC);
bse.setReady(id);
bse.onSurfacePlacement();
@@ -278,7 +283,7 @@ public class SyncEngineTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener listener = mock(
BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(listener);
+ int id = startSyncSet(bse, listener);
bse.addToSyncSet(id, parentWC);
bse.setReady(id);
bse.onSurfacePlacement();
@@ -317,7 +322,7 @@ public class SyncEngineTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener listener = mock(
BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(listener);
+ int id = startSyncSet(bse, listener);
bse.addToSyncSet(id, parentWC);
final BLASTSyncEngine.SyncGroup syncGroup = parentWC.mSyncGroup;
bse.setReady(id);
@@ -350,6 +355,33 @@ public class SyncEngineTests extends WindowTestsBase {
assertEquals(SYNC_STATE_NONE, botChildWC.mSyncState);
}
+ @Test
+ public void testNonBlastMethod() {
+ mAppWindow = createWindow(null, TYPE_BASE_APPLICATION, "mAppWindow");
+
+ final BLASTSyncEngine bse = createTestBLASTSyncEngine();
+
+ BLASTSyncEngine.TransactionReadyListener listener = mock(
+ BLASTSyncEngine.TransactionReadyListener.class);
+
+ int id = startSyncSet(bse, listener, METHOD_NONE);
+ bse.addToSyncSet(id, mAppWindow.mToken);
+ mAppWindow.prepareSync();
+ assertFalse(mAppWindow.shouldSyncWithBuffers());
+
+ mAppWindow.removeImmediately();
+ }
+
+ static int startSyncSet(BLASTSyncEngine engine,
+ BLASTSyncEngine.TransactionReadyListener listener) {
+ return startSyncSet(engine, listener, METHOD_BLAST);
+ }
+
+ static int startSyncSet(BLASTSyncEngine engine,
+ BLASTSyncEngine.TransactionReadyListener listener, int method) {
+ return engine.startSyncSet(listener, BLAST_TIMEOUT_DURATION, "", method);
+ }
+
static class TestWindowContainer extends WindowContainer {
final boolean mWaiter;
boolean mVisibleRequested = true;
diff --git a/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java b/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java
index 1e64e469fe7f..f5304d00faab 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java
@@ -18,6 +18,13 @@ package com.android.server.wm;
import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
import static android.view.DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS;
+import static android.view.InsetsState.ITYPE_BOTTOM_DISPLAY_CUTOUT;
+import static android.view.InsetsState.ITYPE_CLIMATE_BAR;
+import static android.view.InsetsState.ITYPE_LEFT_DISPLAY_CUTOUT;
+import static android.view.InsetsState.ITYPE_NAVIGATION_BAR;
+import static android.view.InsetsState.ITYPE_RIGHT_DISPLAY_CUTOUT;
+import static android.view.InsetsState.ITYPE_STATUS_BAR;
+import static android.view.InsetsState.ITYPE_TOP_DISPLAY_CUTOUT;
import static android.view.WindowManagerPolicyConstants.NAV_BAR_BOTTOM;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
@@ -26,12 +33,9 @@ import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyInt;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doAnswer;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.eq;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.Mockito.doReturn;
-
import android.annotation.Nullable;
import android.content.Context;
import android.content.res.Configuration;
@@ -43,6 +47,7 @@ import android.util.DisplayMetrics;
import android.view.Display;
import android.view.DisplayCutout;
import android.view.DisplayInfo;
+import android.view.WindowInsets;
import com.android.server.wm.DisplayWindowSettings.SettingsProvider.SettingsEntry;
@@ -204,7 +209,26 @@ class TestDisplayContent extends DisplayContent {
doReturn(true).when(newDisplay).supportsSystemDecorations();
doReturn(true).when(displayPolicy).hasNavigationBar();
doReturn(NAV_BAR_BOTTOM).when(displayPolicy).navigationBarPosition(anyInt());
- doReturn(20).when(displayPolicy).getNavigationBarHeight(anyInt());
+ doReturn(Insets.of(0, 0, 0, 20)).when(displayPolicy).getInsets(any(),
+ eq(WindowInsets.Type.displayCutout() | WindowInsets.Type.navigationBars()));
+ doReturn(Insets.of(0, 20, 0, 20)).when(displayPolicy).getInsets(any(),
+ eq(WindowInsets.Type.displayCutout() | WindowInsets.Type.navigationBars()
+ | WindowInsets.Type.statusBars()));
+ final int[] nonDecorTypes = new int[]{
+ ITYPE_TOP_DISPLAY_CUTOUT, ITYPE_RIGHT_DISPLAY_CUTOUT,
+ ITYPE_BOTTOM_DISPLAY_CUTOUT, ITYPE_LEFT_DISPLAY_CUTOUT, ITYPE_NAVIGATION_BAR
+ };
+ doReturn(Insets.of(0, 0, 0, 20)).when(displayPolicy).getInsetsWithInternalTypes(
+ any(),
+ eq(nonDecorTypes));
+ final int[] stableTypes = new int[]{
+ ITYPE_TOP_DISPLAY_CUTOUT, ITYPE_RIGHT_DISPLAY_CUTOUT,
+ ITYPE_BOTTOM_DISPLAY_CUTOUT, ITYPE_LEFT_DISPLAY_CUTOUT,
+ ITYPE_NAVIGATION_BAR, ITYPE_STATUS_BAR, ITYPE_CLIMATE_BAR
+ };
+ doReturn(Insets.of(0, 20, 0, 20)).when(displayPolicy).getInsetsWithInternalTypes(
+ any(),
+ eq(stableTypes));
} else {
doReturn(false).when(displayPolicy).hasNavigationBar();
doReturn(false).when(displayPolicy).hasStatusBar();
diff --git a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
index 85ac7bd96854..55ca5fa65fce 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java
@@ -57,6 +57,7 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.IBinder;
@@ -73,6 +74,7 @@ import android.window.RemoteTransition;
import android.window.TaskFragmentOrganizer;
import android.window.TransitionInfo;
+import androidx.annotation.NonNull;
import androidx.test.filters.SmallTest;
import org.junit.Test;
@@ -1117,6 +1119,36 @@ public class TransitionTests extends WindowTestsBase {
assertTrue(targets.contains(activity));
}
+ @Test
+ public void testTransitionVisibleChange() {
+ registerTestTransitionPlayer();
+ final ActivityRecord app = createActivityRecord(mDisplayContent);
+ final Transition transition = new Transition(TRANSIT_OPEN, 0 /* flags */,
+ app.mTransitionController, mWm.mSyncEngine);
+ app.mTransitionController.moveToCollecting(transition, BLASTSyncEngine.METHOD_NONE);
+ final ArrayList<WindowContainer> freezeCalls = new ArrayList<>();
+ transition.setContainerFreezer(new Transition.IContainerFreezer() {
+ @Override
+ public boolean freeze(@NonNull WindowContainer wc, @NonNull Rect bounds) {
+ freezeCalls.add(wc);
+ return true;
+ }
+
+ @Override
+ public void cleanUp(SurfaceControl.Transaction t) {
+ }
+ });
+ final Task task = app.getTask();
+ transition.collect(task);
+ final Rect bounds = new Rect(task.getBounds());
+ Configuration c = new Configuration(task.getRequestedOverrideConfiguration());
+ bounds.inset(10, 10);
+ c.windowConfiguration.setBounds(bounds);
+ task.onRequestedOverrideConfigurationChanged(c);
+ assertTrue(freezeCalls.contains(task));
+ transition.abort();
+ }
+
private static void makeTaskOrganized(Task... tasks) {
final ITaskOrganizer organizer = mock(ITaskOrganizer.class);
for (Task t : tasks) {
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java
index a62625cea46c..3b64c512ca8f 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java
@@ -42,8 +42,10 @@ import static com.android.dx.mockito.inline.extended.ExtendedMockito.times;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
import static com.android.server.wm.ActivityRecord.State.RESUMED;
+import static com.android.server.wm.BLASTSyncEngine.METHOD_BLAST;
import static com.android.server.wm.WindowContainer.POSITION_TOP;
import static com.android.server.wm.WindowContainer.SYNC_STATE_READY;
+import static com.android.server.wm.WindowState.BLAST_TIMEOUT_DURATION;
import static com.google.common.truth.Truth.assertThat;
@@ -997,7 +999,7 @@ public class WindowOrganizerTests extends WindowTestsBase {
BLASTSyncEngine.TransactionReadyListener transactionListener =
mock(BLASTSyncEngine.TransactionReadyListener.class);
- int id = bse.startSyncSet(transactionListener);
+ int id = bse.startSyncSet(transactionListener, BLAST_TIMEOUT_DURATION, "", METHOD_BLAST);
bse.addToSyncSet(id, task);
bse.setReady(id);
bse.onSurfacePlacement();
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
index 564d3ca2a1c9..6785979e2065 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
@@ -331,6 +331,10 @@ class WindowTestsBase extends SystemServiceTestsBase {
mNavBarWindow.mAttrs.gravity = Gravity.BOTTOM;
mNavBarWindow.mAttrs.paramsForRotation = new WindowManager.LayoutParams[4];
mNavBarWindow.mAttrs.setFitInsetsTypes(0);
+ mNavBarWindow.mAttrs.layoutInDisplayCutoutMode =
+ LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
+ mNavBarWindow.mAttrs.privateFlags |=
+ WindowManager.LayoutParams.PRIVATE_FLAG_LAYOUT_SIZE_EXTENDED_BY_CUTOUT;
for (int rot = Surface.ROTATION_0; rot <= Surface.ROTATION_270; rot++) {
mNavBarWindow.mAttrs.paramsForRotation[rot] =
getNavBarLayoutParamsForRotation(rot);
@@ -381,6 +385,9 @@ class WindowTestsBase extends SystemServiceTestsBase {
lp.height = height;
lp.gravity = gravity;
lp.setFitInsetsTypes(0);
+ lp.privateFlags |=
+ WindowManager.LayoutParams.PRIVATE_FLAG_LAYOUT_SIZE_EXTENDED_BY_CUTOUT;
+ lp.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
return lp;
}
diff --git a/tests/testables/tests/AndroidManifest.xml b/tests/testables/tests/AndroidManifest.xml
index 2bfb04fdb765..1731f6be4bf2 100644
--- a/tests/testables/tests/AndroidManifest.xml
+++ b/tests/testables/tests/AndroidManifest.xml
@@ -21,7 +21,7 @@
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
<uses-permission android:name="android.permission.MANAGE_USERS" />
- <application android:debuggable="true">
+ <application android:debuggable="true" android:testOnly="true">
<uses-library android:name="android.test.runner" />
</application>
diff --git a/tests/testables/tests/AndroidTest.xml b/tests/testables/tests/AndroidTest.xml
new file mode 100644
index 000000000000..de1165fca1a2
--- /dev/null
+++ b/tests/testables/tests/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2022 The Android Open Source Project
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+<configuration description="Runs Testable Tests.">
+ <option name="test-tag" value="TestablesTests" />
+ <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+ <option name="cleanup-apks" value="true" />
+ <option name="install-arg" value="-t" />
+ <option name="test-file-name" value="TestablesTests.apk" />
+ </target_preparer>
+ <test class="com.android.tradefed.testtype.AndroidJUnitTest">
+ <option name="package" value="com.android.testables"/>
+ </test>
+</configuration> \ No newline at end of file
diff --git a/tools/aapt2/dump/DumpManifest.cpp b/tools/aapt2/dump/DumpManifest.cpp
index 39ac24b29f35..b3165d320e9b 100644
--- a/tools/aapt2/dump/DumpManifest.cpp
+++ b/tools/aapt2/dump/DumpManifest.cpp
@@ -1981,10 +1981,11 @@ class Action : public ManifestExtractor::Element {
if (ElementCast<Activity>(parent_stack[1])) {
// Detects the presence of a particular type of activity.
Activity* activity = ElementCast<Activity>(parent_stack[1]);
- auto map = std::map<std::string, std::string>({
- { "android.intent.action.MAIN" , "main" },
- { "android.intent.action.VIDEO_CAMERA" , "camera" },
- { "android.intent.action.STILL_IMAGE_CAMERA_SECURE" , "camera-secure" },
+ static const auto map = std::map<std::string, std::string>({
+ {"android.intent.action.MAIN", "main"},
+ {"android.media.action.VIDEO_CAMERA", "camera"},
+ {"android.media.action.STILL_IMAGE_CAMERA", "camera"},
+ {"android.media.action.STILL_IMAGE_CAMERA_SECURE", "camera-secure"},
});
auto entry = map.find(action);
@@ -2735,10 +2736,9 @@ bool ManifestExtractor::Extract(android::IDiagnostics* diag) {
auto it = apk_->GetFileCollection()->Iterator();
while (it->HasNext()) {
auto file_path = it->Next()->GetSource().path;
- size_t pos = file_path.find("lib/");
- if (pos != std::string::npos) {
- file_path = file_path.substr(pos + 4);
- pos = file_path.find('/');
+ if (file_path.starts_with("lib/")) {
+ file_path = file_path.substr(4);
+ size_t pos = file_path.find('/');
if (pos != std::string::npos) {
file_path = file_path.substr(0, pos);
}
diff --git a/tools/aapt2/integration-tests/DumpTest/components.apk b/tools/aapt2/integration-tests/DumpTest/components.apk
index deb55ea6fda3..a34ec83f3dae 100644
--- a/tools/aapt2/integration-tests/DumpTest/components.apk
+++ b/tools/aapt2/integration-tests/DumpTest/components.apk
Binary files differ
diff --git a/tools/aapt2/integration-tests/DumpTest/components_full_proto.txt b/tools/aapt2/integration-tests/DumpTest/components_full_proto.txt
index bd7673616ddc..8e733a5db034 100644
--- a/tools/aapt2/integration-tests/DumpTest/components_full_proto.txt
+++ b/tools/aapt2/integration-tests/DumpTest/components_full_proto.txt
@@ -1677,7 +1677,7 @@ xml_files {
attribute {
namespace_uri: "http://schemas.android.com/apk/res/android"
name: "name"
- value: "android.intent.action.VIDEO_CAMERA"
+ value: "android.media.action.VIDEO_CAMERA"
resource_id: 16842755
}
}
@@ -1691,7 +1691,7 @@ xml_files {
attribute {
namespace_uri: "http://schemas.android.com/apk/res/android"
name: "name"
- value: "android.intent.action.STILL_IMAGE_CAMERA_SECURE"
+ value: "android.media.action.STILL_IMAGE_CAMERA_SECURE"
resource_id: 16842755
}
}
diff --git a/tools/lint/OWNERS b/tools/lint/OWNERS
index 7c0451900e32..2c526a1e239e 100644
--- a/tools/lint/OWNERS
+++ b/tools/lint/OWNERS
@@ -2,4 +2,5 @@ brufino@google.com
jsharkey@google.com
per-file *CallingSettingsNonUserGetterMethods* = file:/packages/SettingsProvider/OWNERS
+per-file *RegisterReceiverFlagDetector* = jacobhobbie@google.com