From b94ca4f2ad6f28e492e9eca6acd2ec2b7e1bba71 Mon Sep 17 00:00:00 2001 From: christosts Date: Tue, 8 Mar 2022 17:18:14 +0000 Subject: [PATCH] Only COMMAND_PLAY starts the service in the foreground This change makes all notification actions start MediaSessionService in the background except COMMAND_PLAY which starts the service in the foreground. This is to avoid ANRs that are raised if we don't call MediaSessionService.startForeground() within 5 seconds since the service was started in the foreground. We only call MediaSessionService.startForeground() when Player.getPlayWhenReady() returns true, and only COMMAND_PLAY sets playWhenReady to true. Issue: androidx/media#20 #minor-release PiperOrigin-RevId: 433229604 --- .../java/androidx/media3/session/DefaultActionFactory.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/libraries/session/src/main/java/androidx/media3/session/DefaultActionFactory.java b/libraries/session/src/main/java/androidx/media3/session/DefaultActionFactory.java index bcc12059225..a2085ccabd8 100644 --- a/libraries/session/src/main/java/androidx/media3/session/DefaultActionFactory.java +++ b/libraries/session/src/main/java/androidx/media3/session/DefaultActionFactory.java @@ -64,8 +64,8 @@ public PendingIntent createMediaActionPendingIntent(@Command long command) { Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.setComponent(new ComponentName(service, service.getClass())); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); - if (Util.SDK_INT >= 26 && command != COMMAND_PAUSE && command != COMMAND_STOP) { - return Api26.createPendingIntent(service, keyCode, intent); + if (Util.SDK_INT >= 26 && command == COMMAND_PLAY) { + return Api26.createForegroundServicePendingIntent(service, keyCode, intent); } else { return PendingIntent.getService( service, @@ -137,7 +137,8 @@ public Bundle getCustomActionExtras(Intent intent) { private static final class Api26 { private Api26() {} - public static PendingIntent createPendingIntent(Service service, int keyCode, Intent intent) { + public static PendingIntent createForegroundServicePendingIntent( + Service service, int keyCode, Intent intent) { return PendingIntent.getForegroundService( service, /* requestCode= */ keyCode, intent, PendingIntent.FLAG_IMMUTABLE); }