fix(auto): keep the service alive through interruptions, restore local music

Four car reports, two root causes.

1. Local music vanished from the Android Auto menu. Self-inflicted, by
c1afe72 yesterday.

That commit moved registrarFuenteNavegacion above every await to keep a
headless engine from dying before it ran -- but left
registrarFuenteMusicaLocal below `await SharedPreferences.getInstance()`.
The root menu decides whether to offer "Música Local" with
`fuenteLocal != null && await fuenteLocal.hayCarpetaConfigurada()`, so
the car could now get a root response in the window between the two
registrations, find a null source, and be told there is no local music.
Android Auto caches the browse root, so it stayed missing for the whole
session. Before the reorder both registrations sat together after the
await and the window did not exist.

FuenteMusicaLocalAutoImpl never needed prefs to be CONSTRUCTED -- it
resolves them lazily per call, the same convention ServicioAlarmas uses
-- so it now registers beside the station source, above every await, and
the window is gone rather than narrowed.

2. PluriWave disappeared from the Auto pane mid-drive, the playback
screen sat frozen, and the equalizer was lost on every navigation
prompt. One cause for all three.

androidWillPauseWhenDucked: true made audio_session translate Android's
AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK into a full PAUSE. In a car that
fires constantly: every navigation instruction, every speed-camera
warning, every voice assistant. And a pause publishes playing:false,
which AudioService.setState turns into exitPlayingState() and, with
androidStopForegroundOnPause: true, into stopForeground(...). The
plugin's own doc for that flag says what follows: "while in this lower
priority state, the operating system will also be able to kill your
service at any time to reclaim resources". A killed service is a media
session that vanishes from the car pane -- and another media app takes
the slot.

Now the app ducks instead of pausing, so playing stays true and session,
notification and pane all survive an interruption; and the service stays
foreground even on a real pause, so a genuine one is not a death
sentence either. androidNotificationOngoing goes to false because the
plugin asserts it implies stopForegroundOnPause, and nothing is lost: a
foreground service already forces the notification to be ongoing.

A real, non-duckable focus loss (a phone call) still pauses and still
auto-resumes -- asserted, so the duck change cannot silently turn a call
into a station playing over it.

3. Previous/next on the car playback screen, for stations too.

skipToPrevious/skipToNext are now advertised unconditionally, since
Android Auto only draws those buttons when the app declares support.
They are no longer inert without a local queue: they walk the narrowest
list the current station belongs to -- favourites, then my stations,
then the catalogue -- wrapping at both ends, because a button that goes
dead at the end of a list reads as broken on a screen with no visible
list position. Matching is by uuid so a refreshed snapshot still
resolves, and a station in no list leaves playback untouched.

The equalizer toggle still fits alongside them: prev/next take their two
reserved slots and the equalizer claims the remaining custom-action room
because construirControlesTransporte places it before MediaControl.stop.

The phone notification is deliberately untouched: `controls` still gates
skip on an active queue, so nativeActions and
androidCompactActionIndices are byte-identical. Only systemActions
changed, and only the car reads those.

Tests: 1146 -> 1158.
This commit is contained in:
2026-08-06 19:49:57 +02:00
parent 1d8c9c57bc
commit 3398d02a43
8 changed files with 425 additions and 42 deletions
+57 -10
View File
@@ -735,8 +735,14 @@ class PluriWaveAudioHandler extends BaseAudioHandler
MediaAction.playFromMediaId,
MediaAction.playFromSearch,
MediaAction.seek,
if (colaActiva) MediaAction.skipToPrevious,
if (colaActiva) MediaAction.skipToNext,
// Previous/next are advertised ALWAYS now, not only for a local
// queue. Android Auto reserves those two slots and only hands the
// space to custom actions when the app declares no support, so
// this is what puts prev/next on the car's transport row -- and
// `skipToNext`/`skipToPrevious` fall back to station-to-station
// skipping when there is no queue, so neither button is inert.
MediaAction.skipToPrevious,
MediaAction.skipToNext,
},
androidCompactActionIndices: [colaActiva ? 1 : 0],
processingState: mapearEstadoProceso(
@@ -1485,13 +1491,19 @@ class PluriWaveAudioHandler extends BaseAudioHandler
Future<void> seek(Duration position) => _player.seek(position);
/// Moves to the next queued track (Design ADR-3/ADR-4, Phase 3 task
/// 3.6): a no-op when no local queue is active. Past the last track,
/// clears the queue and stops — mirroring auto-advance's end-of-queue
/// behavior (no wraparound).
/// 3.6). Past the last track, clears the queue and stops — mirroring
/// auto-advance's end-of-queue behavior (no wraparound).
///
/// With NO local queue this now moves to the next STATION instead of doing
/// nothing: the car's transport row offers previous/next for radio too,
/// and a button that is present but inert is worse than no button.
@override
Future<void> skipToNext() async {
final cola = _colaLocal;
if (cola == null) return;
if (cola == null) {
await _saltarEmisora(haciaAtras: false);
return;
}
final siguiente = cola.conSiguiente();
if (siguiente == null) {
_desactivarCola();
@@ -1502,18 +1514,53 @@ class PluriWaveAudioHandler extends BaseAudioHandler
await _reproducirEntradaCola(siguiente.actual);
}
/// Moves to the previous queued track (Design ADR-4, Phase 3 task 3.6):
/// a no-op when no local queue is active. Clamps at the first track
/// (restarts it) instead of wrapping to the last one.
/// Moves to the previous queued track (Design ADR-4, Phase 3 task 3.6).
/// Clamps at the first track (restarts it) instead of wrapping to the last
/// one. With no local queue, moves to the previous STATION — see
/// [skipToNext].
@override
Future<void> skipToPrevious() async {
final cola = _colaLocal;
if (cola == null) return;
if (cola == null) {
await _saltarEmisora(haciaAtras: true);
return;
}
final anterior = cola.conAnterior();
_colaLocal = anterior;
await _reproducirEntradaCola(anterior.actual);
}
/// Station-to-station skipping for the car's transport row.
///
/// The list to walk is resolved by [listaParaSaltoEmisora]: the narrowest
/// list the current station actually belongs to, favourites first. Anything
/// unresolvable — no source, no current station, a station that is in no
/// list, a single-entry list — leaves playback untouched. Never throws;
/// this runs from a hardware/steering-wheel button and an exception here
/// would surface as the app going silent mid-drive.
Future<void> _saltarEmisora({required bool haciaAtras}) async {
try {
final fuente = _fuenteNavegacionGlobal;
final actual = emisoraActual;
if (fuente == null || actual == null) return;
final lista = listaParaSaltoEmisora(
actual: actual,
favoritos: await fuente.favoritos(),
misEmisoras: await fuente.misEmisoras(),
todas: await fuente.todas(),
);
final destino = emisoraVecina(actual, lista, haciaAtras: haciaAtras);
if (destino == null) return;
await playMediaItem(mediaItemParaEmisora(destino, l10n: _textos));
} catch (e) {
developer.log(
'[PluriWave] Error saltando de emisora: $e',
name: 'ServicioAudio',
level: 900,
);
}
}
/// Dispatches the equalizer's only custom action (decision
/// `auto/ecualizador-diseno`): `accionEqToggle` flips on/off, delegating
/// to the existing [setEcualizadorActivo] — the SAME entry point the