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
This commit is contained in:
christosts 2022-03-08 17:18:14 +00:00 committed by Ian Baker
parent 2f4630a8e8
commit b94ca4f2ad

View File

@ -64,8 +64,8 @@ import androidx.media3.common.util.Util;
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 @@ import androidx.media3.common.util.Util;
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);
}