From 8cbc97407079cfe2d3d7882a2dea110f6d249590 Mon Sep 17 00:00:00 2001 From: Hui Yu Date: Thu, 22 Apr 2021 10:40:11 -0700 Subject: [PATCH] Move postFgsNotificationLocked() to outer block. Some apps call Service.startForeground() multiple times with different Notification objects to update the notification. The change I049070f343f578fa3e9f6bb4dab914da5b23672a moved postFgsNotificationLocked() from outer block to inner block for the purpose of updating mFgsNotificationDeferred and mFgsNotificationShown fields before the logForegroundServiceStateChanged() call. This has changed the behavior and apps can not use multiple Service.startForeground() calls to update notification any more. To avoid breaking apps, move postFgsNotificationLocked() to outer block. Bug: 185523487 Test: b/185523487 test. Change-Id: Idc6ea831cc8943dc24b85de9989c3aa3d99e2ffa --- .../com/android/server/am/ActiveServices.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java index 10cf1846da6f8..c7994c36d7d85 100644 --- a/services/core/java/com/android/server/am/ActiveServices.java +++ b/services/core/java/com/android/server/am/ActiveServices.java @@ -1815,6 +1815,7 @@ public final class ActiveServices { notification.flags |= Notification.FLAG_FOREGROUND_SERVICE; r.foregroundNoti = notification; r.foregroundServiceType = foregroundServiceType; + boolean enterForeground = false; if (!r.isForeground) { final ServiceMap smap = getServiceMapLocked(r.userId); if (smap != null) { @@ -1840,6 +1841,7 @@ public final class ActiveServices { active.mNumActive++; } r.isForeground = true; + enterForeground = true; r.mStartForegroundCount++; r.mFgsEnterTime = SystemClock.uptimeMillis(); if (!stopProcStatsOp) { @@ -1851,16 +1853,23 @@ public final class ActiveServices { } else { stopProcStatsOp = false; } - postFgsNotificationLocked(r); + mAm.mAppOpsService.startOperation( AppOpsManager.getToken(mAm.mAppOpsService), AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null, true, false, "", false); + registerAppOpCallbackLocked(r); + mAm.updateForegroundServiceUsageStats(r.name, r.userId, true); + } + // Even if the service is already a FGS, we need to update the notification, + // so we need to call it again. + postFgsNotificationLocked(r); + if (enterForeground) { + // Because we want to log what's updated in postFgsNotificationLocked(), + // this must be called after postFgsNotificationLocked(). logForegroundServiceStateChanged(r, FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER, 0); - registerAppOpCallbackLocked(r); - mAm.updateForegroundServiceUsageStats(r.name, r.userId, true); } if (r.app != null) { updateServiceForegroundLocked(psr, true);