Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix stale MediaSession after long background idle

Nathan Poulson57a4d59a599a
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index efac5362..7cd899fe 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -396,6 +396,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
if (state == AppLifecycleState.resumed) {
context.read<LibraryProvider>().onAppForegrounded();
SleepTimerService().onAppForegrounded();
+ AudioPlayerService.onAppForegrounded();
_refreshDataForTab(_currentIndex);
// Check auto sleep in case we resumed into the window
SleepTimerService().checkAutoSleep();
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 93589c7c..b3431555 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1063,8 +1063,11 @@ class AudioPlayerService extends ChangeNotifier {
androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
androidWillPauseWhenDucked: true,
));
- await session.setActive(true);
- debugPrint('[Battery] AudioSession ACTIVATED');
+ // Don't activate the session here — defer to first playback.
+ // Activating during init creates a stale MediaSession that Android
+ // can garbage-collect after hours in background, leaving bluetooth /
+ // notification / widget controls permanently broken.
+ // play() and startLocalPlayback() call setActive(true) before playing.
_interruptSub?.cancel();
_interruptSub = session.interruptionEventStream.listen((event) async {
@@ -1146,6 +1149,35 @@ class AudioPlayerService extends ChangeNotifier {
});
}
+ /// Refresh the media session when the app returns to foreground.
+ /// After a long background idle, Android can garbage-collect the stale
+ /// MediaSession, leaving bluetooth / notification / widget controls dead.
+ /// Re-activating the audio session and re-pushing handler state recovers it.
+ static Future<void> onAppForegrounded() async {
+ final service = _instance;
+ if (!service.hasBook) return;
+ // Re-activate audio session to get a fresh system token
+ if (!_audioFocusDisabled) {
+ try { (await AudioSession.instance).setActive(true); } catch (_) {}
+ }
+ // Re-push playback state so the system re-registers the MediaSession
+ _handler?.refreshPlaybackState();
+ // Re-push media item so notification metadata is fresh
+ if (service._currentItemId != null && service._currentTitle != null) {
+ final chapterTitle = service._lastNotifiedChapterIndex >= 0 && service._chapters.isNotEmpty
+ ? (service._chapters[service._lastNotifiedChapterIndex] as Map<String, dynamic>)['title'] as String?
+ : null;
+ service._pushMediaItem(
+ service._currentItemId!,
+ service._currentTitle!,
+ service._currentAuthor ?? '',
+ service._currentCoverUrl,
+ service._totalDuration,
+ chapter: chapterTitle,
+ );
+ }
+ }
+
String? _currentEpisodeId;
String? get currentEpisodeId => _currentEpisodeId;