From 601eaba7a6dcce963d5a3547d939ea41404ad3fe Mon Sep 17 00:00:00 2001 From: christosts Date: Wed, 19 Oct 2022 13:41:26 +0000 Subject: [PATCH] Use Service.stopForeground(int) on API 24+ The MediaNotficationManager stops the service from the foreground calling Service.stopForeground(boolean) which is deprecated in API 33. This change calls Service.stopForeground(int), which was added in API 24. #minor-release PiperOrigin-RevId: 482190332 --- .../session/MediaNotificationManager.java | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/libraries/session/src/main/java/androidx/media3/session/MediaNotificationManager.java b/libraries/session/src/main/java/androidx/media3/session/MediaNotificationManager.java index 4ed2e8f52c..679888d52e 100644 --- a/libraries/session/src/main/java/androidx/media3/session/MediaNotificationManager.java +++ b/libraries/session/src/main/java/androidx/media3/session/MediaNotificationManager.java @@ -15,6 +15,8 @@ */ package androidx.media3.session; +import static android.app.Service.STOP_FOREGROUND_DETACH; +import static android.app.Service.STOP_FOREGROUND_REMOVE; import static androidx.media3.common.util.Assertions.checkStateNotNull; import android.app.Notification; @@ -229,10 +231,14 @@ import java.util.concurrent.TimeoutException; } } // To hide the notification on all API levels, we need to call both Service.stopForeground(true) - // and notificationManagerCompat.cancel(notificationId). For pre-L devices, we must also call - // Service.stopForeground(true) anyway as a workaround that prevents the media notification from - // being undismissable. - mediaSessionService.stopForeground(removeNotifications || Util.SDK_INT < 21); + // and notificationManagerCompat.cancel(notificationId). + if (Util.SDK_INT >= 24) { + Api24.stopForeground(mediaSessionService, removeNotifications); + } else { + // For pre-L devices, we must call Service.stopForeground(true) anyway as a workaround + // that prevents the media notification from being undismissable. + mediaSessionService.stopForeground(removeNotifications || Util.SDK_INT < 21); + } if (removeNotifications && mediaNotification != null) { notificationManagerCompat.cancel(mediaNotification.notificationId); // Update the notification count so that if a pending notification callback arrives (e.g., a @@ -301,6 +307,17 @@ import java.util.concurrent.TimeoutException; } } + @RequiresApi(24) + private static class Api24 { + + @DoNotInline + public static void stopForeground(MediaSessionService service, boolean removeNotification) { + service.stopForeground(removeNotification ? STOP_FOREGROUND_REMOVE : STOP_FOREGROUND_DETACH); + } + + private Api24() {} + } + @RequiresApi(29) private static class Api29 {