fix(automotive): stop playback while a vehicle restricts the app

Plezy declares appCategory="video", so on Android Automotive OS it is a
parked app bound by car app quality DD-2/DD-3: audio must stop when the
vehicle starts driving and must not be resumable while driving. Two paths
kept audio alive. Music playback ran under a mediaPlayback foreground
service whose lifecycle observer was registered for Apple TV only, so it
never paused when Android backgrounded the app. Video pausing hung off
AppLifecycleState.hidden, which Flutter only synthesizes once Android
delivers onStop; a car without the Automotive compatibility mode delivers
onPause alone, which maps to AppLifecycleState.inactive and the player
ignored.

Gate every path that can start audio on a new lifecycle predicate,
automotivePlaybackAllowed, which permits playback on a car only while the
app is resumed and fails closed on an unknown lifecycle state. That covers
explicit play, gapless arming and track transitions, live retry and
channel switch, frame-rate-match resume, VOD/live startup, and the queue
navigation commands of the OS media session, plus a last-resort pause for
when the platform player resumes itself on native audio-focus regain.
Playback authority on the media-session router is deliberately left alone:
the router consumes a denied event, so gating it would swallow PauseEvent
and leave the OS unable to stop audio. Reacting to lifecycle callbacks is
the mechanism the platform documents as sufficient, so no android.car
dependency is added.

The music queue no longer requests POST_NOTIFICATIONS on a car, where the
foreground service and its notification never start: there is nothing to
authorize, and the prompt would take focus and make the gate discard the
first play intent.

Detect the form factor too: FEATURE_AUTOMOTIVE now vetoes the Android TV
verdict, so a rotary-only head unit no longer inherits the leanback
experience. Picture-in-picture is gated on FEATURE_PICTURE_IN_PICTURE,
which cars lack, so the app's UI cannot stay on screen while driving, and
nothing forces a preferred orientation on a fixed-orientation display.
This commit is contained in:
edde746
2026-07-28 23:28:25 +02:00
parent 8aa836d106
commit 41ffaa7f2b
19 changed files with 768 additions and 50 deletions
+40
View File
@@ -0,0 +1,40 @@
import 'package:flutter/widgets.dart';
import '../utils/platform_detector.dart';
/// Android Automotive OS driver-distraction gating for Plezy's `video` app
/// category (car app quality `DD-2` / `DD-3`).
///
/// While a vehicle's user-experience restrictions are active the system hides
/// the app's activity. That delivers `onPause` — Flutter
/// [AppLifecycleState.inactive] — at minimum; only devices carrying the
/// Automotive compatibility mode go on to deliver `onStop`
/// ([AppLifecycleState.hidden] then [AppLifecycleState.paused]). Reacting to
/// lifecycle callbacks is the mechanism the platform documents as sufficient,
/// so playback authority is derived from lifecycle state alone and no
/// `android.car` dependency is required.
///
/// Two obligations follow from `DD-2`, and this single predicate serves both:
/// audio must stop when driving starts, and it must not be resumable while
/// driving. The second obligation covers every path that can start audio, not
/// just OS media-session commands — a gapless track transition or queue
/// auto-advance landing just after the lifecycle pause must fail closed too.
///
/// The gate itself fails closed: an unknown (null) lifecycle state denies
/// playback so a command arriving before the first lifecycle message cannot
/// slip through; nothing is playing that early, so the strictness costs nothing.
bool automotivePlaybackAllowed({required bool isAutomotive, required AppLifecycleState? state}) {
if (!isAutomotive) return true;
return state == AppLifecycleState.resumed;
}
/// [automotivePlaybackAllowed] against the ambient form factor and lifecycle,
/// for owners that hold no injected lifecycle state of their own.
///
/// Short-circuits before reading [WidgetsBinding.instance] so this stays usable
/// from plain `test()` suites, where the binding is not initialized and the
/// `instance` getter throws.
bool automotivePlaybackAllowedNow() {
if (!PlatformDetector.isAutomotive()) return true;
return automotivePlaybackAllowed(isAutomotive: true, state: WidgetsBinding.instance.lifecycleState);
}
@@ -14,6 +14,7 @@ import '../../mpv/player/player.dart';
import '../../utils/app_logger.dart';
import '../../utils/notification_permission.dart';
import '../../utils/platform_detector.dart';
import '../driver_distraction.dart';
import '../media_control_router.dart';
import '../media_controls_manager.dart';
import '../multi_server_manager.dart';
@@ -74,10 +75,10 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
_coordinator = coordinator ?? PlaybackCoordinator.instance,
_volumePersistenceWriter = volumePersistenceWriter ?? _writePersistedVolume {
_coordinator.registerMusicSession(stopAndDispose: _stopForVideoClaim);
// tvOS has no background-audio session in v1 pause on backgrounding so
// audio doesn't play over other apps / the home screen. Other platforms
// keep playing under their OS media session.
if (PlatformDetector.isAppleTV()) {
// tvOS has no background-audio session in v1, so it pauses on
// backgrounding. AAOS must stop audio while driving per DD-2. Other
// platforms keep playing under their OS media session.
if (PlatformDetector.isAppleTV() || PlatformDetector.isAutomotive()) {
_observesLifecycle = true;
WidgetsBinding.instance.addObserver(this);
}
@@ -287,7 +288,15 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
// Android 13+: the background playback notification needs
// POST_NOTIFICATIONS. Fire-and-forget — playback and the foreground
// service run regardless; a denial only hides the notification.
unawaited(NotificationPermission.ensure());
//
// Skipped on a car, where `setBackgroundMode(false)` means the foreground
// service and its notification never start, so there is nothing to
// authorize. The prompt would also take focus, leaving the app briefly not
// resumed, and the automotive gate would then open the track paused and
// silently drop the user's play intent.
if (!PlatformDetector.isAutomotive()) {
unawaited(NotificationPermission.ensure());
}
final generation = ++_generation;
_invalidateArmRequests();
_finalizeCurrentTrack();
@@ -327,7 +336,8 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
// Re-asserted per open (cheap, idempotent): the native side drops the
// background-mode opt-in when the user swipes the task away, so a
// session that survives task removal heals itself here.
unawaited(_mediaControls?.setBackgroundMode(true));
// Passing false on AAOS also heals any stale opt-in from an earlier session.
unawaited(_mediaControls?.setBackgroundMode(!PlatformDetector.isAutomotive()));
// Clear any native arm left over from the previous item before the open
// replaces it, so a stray transition can't fire mid-switch.
@@ -358,8 +368,9 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
}
if (generation != _generation || _player != player) return;
final shouldPlay = play && automotivePlaybackAllowedNow();
try {
await player.open(Media(source.url, headers: source.headers), play: play);
await player.open(Media(source.url, headers: source.headers), play: shouldPlay);
} catch (e, st) {
appLogger.w('Music open failed for ${track.id}', error: e, stackTrace: st);
if (generation == _generation) _handlePlaybackFailure(e);
@@ -367,8 +378,13 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
}
if (generation != _generation || _player != player) return;
final playbackStarted = shouldPlay && automotivePlaybackAllowedNow();
if (shouldPlay && !playbackStarted) {
await player.pause();
if (generation != _generation || _player != player) return;
}
committedPlayer = player;
_setStatus(play ? MusicPlaybackStatus.playing : MusicPlaybackStatus.paused);
_setStatus(playbackStarted ? MusicPlaybackStatus.playing : MusicPlaybackStatus.paused);
_bindTrackServices(track, source);
} finally {
// A stale open must never release a newer open's ownership. Only a
@@ -456,7 +472,7 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
}
void _requestArmNext() {
if (_disposed) return;
if (_disposed || !automotivePlaybackAllowedNow()) return;
_armRequestGeneration++;
_armRequestPending = true;
_ensureArmDrain();
@@ -502,6 +518,7 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
}
Future<bool> _trySetNext(Player player, Media? media) async {
if (media != null && !automotivePlaybackAllowedNow()) return false;
try {
await player.setNext(media);
return true;
@@ -559,14 +576,19 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
}
void _onPlayingChanged(bool isPlaying) {
final playbackAllowed = automotivePlaybackAllowedNow();
final shouldBePlaying = isPlaying && playbackAllowed;
if (isPlaying && !playbackAllowed) {
unawaited(_player?.pause());
}
if (_status == MusicPlaybackStatus.playing || _status == MusicPlaybackStatus.paused) {
_setStatus(isPlaying ? MusicPlaybackStatus.playing : MusicPlaybackStatus.paused);
unawaited(_tracker?.sendProgress(isPlaying ? 'playing' : 'paused'));
_setStatus(shouldBePlaying ? MusicPlaybackStatus.playing : MusicPlaybackStatus.paused);
unawaited(_tracker?.sendProgress(shouldBePlaying ? 'playing' : 'paused'));
}
final player = _player;
if (player != null) {
_mediaControls?.updatePlaybackState(
isPlaying: player.state.isActive,
isPlaying: shouldBePlaying && player.state.isActive,
position: player.currentPosition,
speed: 1.0,
force: true,
@@ -629,7 +651,12 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
_currentSource = adopted.source;
_consecutiveFailures = 0;
appLogger.d('Music: transition received "${adopted.track.title}" → cursor ${_queue.cursor}');
_setStatus(MusicPlaybackStatus.playing, forceNotify: true);
if (automotivePlaybackAllowedNow()) {
_setStatus(MusicPlaybackStatus.playing, forceNotify: true);
} else {
unawaited(_player?.pause());
_setStatus(MusicPlaybackStatus.paused, forceNotify: true);
}
_bindTrackServices(_currentTrack!, adopted.source);
_requestArmNext();
}
@@ -808,11 +835,15 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
);
}
/// OS transport commands. Music has no authorization gate: the session only
/// exists while a track is loaded, and that is checked in [_onControlEvent].
/// OS transport commands. Music has no authorization gate for playback: the
/// session only exists while a track is loaded, and that is checked in
/// [_onControlEvent]. The automotive gate deliberately does NOT sit on
/// [MediaControlRouter.canControlPlayback] — the router consumes a denied
/// event, so gating it there would swallow `PauseEvent` and leave the OS
/// unable to stop audio. Starting audio is gated inside [play] instead.
late final _mediaControlRouter = MediaControlRouter(
canControlPlayback: () => true,
canNavigateMediaItems: () => true,
canNavigateMediaItems: automotivePlaybackAllowedNow,
onPlay: () => unawaited(play()),
onPause: () => unawaited(pause()),
onTogglePlayPause: () => unawaited(togglePlayPause()),
@@ -873,6 +904,10 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
@override
Future<void> play() async {
if (!automotivePlaybackAllowedNow()) {
appLogger.d('Music play denied while automotive playback is restricted');
return;
}
final player = _player;
if (player == null || _currentTrack == null) return;
final generation = _generation;
@@ -887,9 +922,23 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
}
_requestArmNext();
}
if (!automotivePlaybackAllowedNow()) {
appLogger.d('Music play denied while automotive playback is restricted');
return;
}
await player.play();
if (!_isCurrentTransport(player, generation)) return;
if (!automotivePlaybackAllowedNow()) {
await player.pause();
if (_isCurrentTransport(player, generation)) {
_setStatus(MusicPlaybackStatus.paused);
}
return;
}
_setStatus(MusicPlaybackStatus.playing);
// A restriction cleared the native arm on the way in; restore it so gapless
// playback survives a park-and-resume cycle.
if (PlatformDetector.isAutomotive()) _requestArmNext();
}
@override
@@ -913,17 +962,36 @@ class MusicPlaybackServiceImpl extends MusicPlaybackService with WidgetsBindingO
return player.state.isActive ? pause() : play();
}
/// Apple TV only (observer registered in the constructor): pause when the
/// app leaves the foreground — tvOS background audio is not attempted in
/// v1, so playback must not continue under the home screen.
/// On Apple TV, pause when the app leaves the foreground because tvOS
/// background audio is not attempted in v1. On AAOS, stop audio whenever
/// the app is not resumed to comply with driver-distraction rule DD-2.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (_disposed) return;
if (state == AppLifecycleState.paused || state == AppLifecycleState.hidden) {
if (isPlaying) {
appLogger.d('App backgrounded on Apple TV — pausing music playback');
unawaited(pause());
if (PlatformDetector.isAutomotive()) {
if (!automotivePlaybackAllowedNow()) {
_invalidateArmRequests();
_rememberStaleArm();
final player = _player;
if (player != null) {
unawaited(_trySetNext(player, null));
}
if (isPlaying) {
appLogger.d('App restricted on Android Automotive — pausing music playback');
unawaited(pause());
}
return;
}
// Restrictions lifted: re-arm the next track that was cleared on entry.
// Playback itself stays paused until the user asks for it.
if (_currentTrack != null) _requestArmNext();
return;
}
if (PlatformDetector.isAppleTV() &&
(state == AppLifecycleState.paused || state == AppLifecycleState.hidden) &&
isPlaying) {
appLogger.d('App backgrounded on Apple TV — pausing music playback');
unawaited(pause());
}
}
+2 -3
View File
@@ -169,14 +169,13 @@ class _AppLocalePref extends Pref<AppLocale> {
Future<void> writeTo(BaseSharedPreferencesService svc, AppLocale value) => svc.writeString(key, value.name);
}
/// Mobile-only with a macOS-disabled-by-default rule; forced off on TV and non-mobile platforms.
/// Uses a macOS-disabled default and is forced off when [PlatformDetector] disables PiP.
class _AutoPipPref extends Pref<bool> {
const _AutoPipPref() : super('auto_pip');
@override
bool readFrom(BaseSharedPreferencesService svc) {
if (!Platform.isAndroid && !Platform.isIOS && !Platform.isMacOS) return false;
if (PlatformDetector.isTV()) return false;
if (!PlatformDetector.supportsPictureInPicture()) return false;
return svc.prefs.getBool(key) ?? !Platform.isMacOS;
}