Files
pluriwave/test/servicios/servicio_audio_session_duck_test.dart
FreeTLab 3398d02a43 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.
2026-08-06 19:49:57 +02:00

121 lines
4.1 KiB
Dart

import 'package:audio_session/audio_session.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pluriwave/servicios/servicio_audio_session.dart';
/// Reported from the car: PluriWave disappeared from the Android Auto pane
/// mid-drive and another media app took its slot, the playback screen sat
/// frozen, and the chosen equalizer was lost whenever navigation, a
/// speed-camera app or the car's voice assistant spoke.
///
/// One cause behind all three. `androidWillPauseWhenDucked: true` made
/// `audio_session` translate Android's AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK
/// into a full PAUSE. In a car that fires on every navigation instruction. A
/// pause publishes `playing: false`, `AudioService.setState` turns that into
/// `exitPlayingState()` and — with `androidStopForegroundOnPause` — into
/// `stopForeground(...)`. The plugin's own doc for that flag: «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.
///
/// Ducking keeps `playing: true` throughout, so session, notification and
/// car pane all survive the interruption.
class _ObjetivoFalso implements ObjetivoAudioInterrumpible {
bool atenuado = false;
int pausas = 0;
int reanudaciones = 0;
int reaplicacionesEq = 0;
@override
bool intencionReproducir = true;
@override
bool estaReproduciendo = true;
@override
Future<void> pausar() async => pausas++;
@override
Future<void> reanudar() async => reanudaciones++;
@override
Future<void> setAtenuado(bool valor) async => atenuado = valor;
@override
Future<void> reaplicarEcualizador() async => reaplicacionesEq++;
}
void main() {
test('un aviso de navegación ATENÚA, nunca pausa', () async {
final objetivo = _ObjetivoFalso();
final servicio = ServicioAudioSession(objetivo: objetivo);
await servicio.manejarInterrupcion(
AudioInterruptionEvent(true, AudioInterruptionType.duck),
);
expect(objetivo.atenuado, isTrue);
expect(
objetivo.pausas,
0,
reason:
'pausar publica playing:false -> exitPlayingState -> el servicio '
'sale de primer plano y Android puede matarlo; ahí es donde la app '
'desaparecía del panel del coche',
);
});
test('al terminar el aviso se recupera el volumen Y se reasienta el '
'ecualizador', () async {
final objetivo = _ObjetivoFalso();
final servicio = ServicioAudioSession(objetivo: objetivo);
await servicio.manejarInterrupcion(
AudioInterruptionEvent(true, AudioInterruptionType.duck),
);
await servicio.manejarInterrupcion(
AudioInterruptionEvent(false, AudioInterruptionType.duck),
);
expect(objetivo.atenuado, isFalse);
expect(
objetivo.reaplicacionesEq,
1,
reason:
'Android puede desactivar en silencio el efecto de esta app cuando '
'otro cliente de mayor prioridad toma el foco, y el id de sesión no '
'cambia, así que el disparador por rotación de sesión no salta',
);
expect(objetivo.pausas, 0);
});
test('una llamada entrante SÍ pausa: no todo es un aviso corto', () async {
// The duck change must not turn a real, non-duckable focus loss into a
// station that keeps playing over a phone call.
final objetivo = _ObjetivoFalso();
final servicio = ServicioAudioSession(objetivo: objetivo);
await servicio.manejarInterrupcion(
AudioInterruptionEvent(true, AudioInterruptionType.pause),
);
expect(objetivo.pausas, 1);
await servicio.manejarInterrupcion(
AudioInterruptionEvent(false, AudioInterruptionType.pause),
);
expect(objetivo.reanudaciones, 1);
expect(objetivo.reaplicacionesEq, 1);
});
test('desconectar los auriculares pausa y NO reanuda solo', () async {
final objetivo = _ObjetivoFalso();
final servicio = ServicioAudioSession(objetivo: objetivo);
await servicio.manejarDesconexionSalida();
expect(objetivo.pausas, 1);
expect(objetivo.reanudaciones, 0);
});
}