A cross platform Audiobookshelf client for Android and iOS
Dart
Use much less battery while paused
Barnabas350053492396
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex 45a3cff6..1bd5929a 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -717,6 +717,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {void _startConnectivityMonitoring() {_connectivitySub?.cancel();+ _connectivityDebounce?.cancel();Connectivity().checkConnectivity().then((result) {_deviceHasConnectivity = !result.contains(ConnectivityResult.none);if (!_deviceHasConnectivity) {@@ -740,6 +741,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {final hasConnectivity = !result.contains(ConnectivityResult.none);_deviceHasConnectivity = hasConnectivity;if (!hasConnectivity) {+ _connectivityDebounce?.cancel();_stopServerPingTimer();_stopLocalProbeTimer();setNetworkOffline(true);@@ -750,25 +752,31 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {}if (_manualOffline) return;- // Got connectivity back - re-probe and potentially come online.- // We pick the active server based on actual reachability, not on- // whether the connectivity list happens to contain wifi this tick.- final reachable =- await _pingActiveServerWithFallback(const Duration(seconds: 5)) != null;- if (reachable) {- setNetworkOffline(false);- if (_rollingDownloadSeries.isNotEmpty) _catchUpRollingDownloads();- _catchUpQueueAutoDownloads();- (this as LibraryProvider).catchUpSubscribedPodcasts();- } else {- debugPrint('[Library] Connectivity changed but server unreachable — starting ping timer');- if (_networkOffline) {- _startServerPingTimer();+ // Coalesce bursts of "connected" events (wifi<->mobile handoff, interface+ // scans) so we don't re-ping the server and re-run catch-up downloads on+ // every blip - that was burning packets and battery on flaky networks.+ _connectivityDebounce?.cancel();+ _connectivityDebounce = Timer(const Duration(seconds: 2), () async {+ // Got connectivity back - re-probe and potentially come online.+ // We pick the active server based on actual reachability, not on+ // whether the connectivity list happens to contain wifi this tick.+ final reachable =+ await _pingActiveServerWithFallback(const Duration(seconds: 5)) != null;+ if (reachable) {+ setNetworkOffline(false);+ if (_rollingDownloadSeries.isNotEmpty) _catchUpRollingDownloads();+ _catchUpQueueAutoDownloads();+ (this as LibraryProvider).catchUpSubscribedPodcasts();} else {- _goOffline();+ debugPrint('[Library] Connectivity changed but server unreachable — starting ping timer');+ if (_networkOffline) {+ _startServerPingTimer();+ } else {+ _goOffline();+ }}- }- _startLocalProbeTimer();+ _startLocalProbeTimer();+ });});}diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dartindex cadd9c08..0405cf4a 100644--- a/lib/providers/_lp_state.dart+++ b/lib/providers/_lp_state.dart@@ -97,6 +97,7 @@ mixin _StateMixin on ChangeNotifier {final Set<String> _locallyFinishedItems = {};StreamSubscription? _connectivitySub;+ Timer? _connectivityDebounce;bool _listeningToDownloads = false;String? _lastAuthKey;bool? _lastUseLocalServer;diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex c555d4f1..a7f46368 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -131,6 +131,7 @@ class LibraryProvider extends ChangeNotifier_lastRssHydrationLibraryId = null;_networkOffline = false;_connectivitySub?.cancel();+ _connectivityDebounce?.cancel();_stopServerPingTimer();_stopHealthCheckTimer();_isLoading = true;@@ -215,6 +216,7 @@ class LibraryProvider extends ChangeNotifier_selectedLibraryId = null;_errorMessage = null;_connectivitySub?.cancel();+ _connectivityDebounce?.cancel();_progressRefreshDebounce?.cancel();_stopServerPingTimer();_stopHealthCheckTimer();diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dartindex 2f37cc42..9f13fc8f 100644--- a/lib/screens/app_shell.dart+++ b/lib/screens/app_shell.dart@@ -131,6 +131,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Tickerfinal _cast = ChromecastService();bool _playerHadBook = false;bool _wasPlaying = false;+ bool _lifecycleBackgrounded = false;String? _lastItemId;bool _expandedIsOpen = false;bool _wasCasting = false;@@ -489,31 +490,57 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker@overridevoid didChangeAppLifecycleState(AppLifecycleState state) {- if (state == AppLifecycleState.resumed) {- // Belt-and-suspenders: never let the nav bar come back hidden after a- // resume. The screens snap their own driver back to shown on next scroll- // anyway, but mirror it here in case the user resumes onto a stale tab.- _navBarAnimController.value = 1.0;- context.read<LibraryProvider>().onAppForegrounded();- SleepTimerService().onAppForegrounded();- AudioPlayerService.onAppForegrounded();- HomeWidgetService().onAppForegrounded();- ReviewService.onAppForegrounded();- _refreshDataForTab(_currentIndex);- // Check auto sleep in case we resumed into the window- SleepTimerService().checkAutoSleep();- _checkForUpdate();- } else if (state == AppLifecycleState.paused) {- context.read<LibraryProvider>().onAppBackgrounded();- SleepTimerService().onAppBackgrounded();- AudioPlayerService.onAppBackgrounded();- HomeWidgetService().onAppBackgrounded();- } else if (state == AppLifecycleState.detached) {- final cast = ChromecastService();- if (cast.isConnected) cast.disconnect();+ switch (state) {+ case AppLifecycleState.resumed:+ _handleAppForegrounded();+ break;+ case AppLifecycleState.hidden:+ case AppLifecycleState.paused:+ // `hidden` fires on desktop (macOS/Windows) when the window is+ // minimized or hidden, where `paused` often never arrives - without+ // handling it, every background timer and the socket keep running at+ // full foreground cadence forever and drain the battery. On mobile+ // `hidden` precedes `paused`; the _lifecycleBackgrounded guard makes+ // the second call a no-op (and stops `hidden` on the way back up from+ // flapping the socket).+ _handleAppBackgrounded();+ break;+ case AppLifecycleState.detached:+ final cast = ChromecastService();+ if (cast.isConnected) cast.disconnect();+ break;+ case AppLifecycleState.inactive:+ break;}}+ void _handleAppForegrounded() {+ if (!_lifecycleBackgrounded) return;+ _lifecycleBackgrounded = false;+ // Belt-and-suspenders: never let the nav bar come back hidden after a+ // resume. The screens snap their own driver back to shown on next scroll+ // anyway, but mirror it here in case the user resumes onto a stale tab.+ _navBarAnimController.value = 1.0;+ context.read<LibraryProvider>().onAppForegrounded();+ SleepTimerService().onAppForegrounded();+ AudioPlayerService.onAppForegrounded();+ HomeWidgetService().onAppForegrounded();+ ReviewService.onAppForegrounded();+ _refreshDataForTab(_currentIndex);+ // Check auto sleep in case we resumed into the window+ SleepTimerService().checkAutoSleep();+ _checkForUpdate();+ }++ void _handleAppBackgrounded() {+ if (_lifecycleBackgrounded) return;+ _lifecycleBackgrounded = true;+ context.read<LibraryProvider>().onAppBackgrounded();+ SleepTimerService().onAppBackgrounded();+ AudioPlayerService.onAppBackgrounded();+ HomeWidgetService().onAppBackgrounded();+ }+@overridevoid didChangeMetrics() {// Orientation change, software keyboard, anything that resizes the window:diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dartindex 6ac8508d..409f590b 100644--- a/lib/services/home_widget_service.dart+++ b/lib/services/home_widget_service.dart@@ -113,11 +113,11 @@ class HomeWidgetService {// Fetch stats in the background so the StatsWidget renders fresh on launch.refreshStats();- // Stats timer runs even while the app is backgrounded so "today" keeps- // ticking on the widget during long listening sessions without needing- // the user to open the app. 15-min cadence matches the refresh throttle.- _statsTimer?.cancel();- _statsTimer = Timer.periodic(_statsThrottle, (_) => refreshStats());+ // Poll stats so "today" keeps ticking on the widget during long listening+ // sessions. Stopped while backgrounded-and-paused (see onAppBackgrounded)+ // so it doesn't drain battery overnight. 15-min cadence matches the+ // refresh throttle.+ _ensureStatsTimer();// Phase 1.4 hand-off heartbeat. The iOS native player core checks this// before driving audio: a recent timestamp means Flutter is alive and@@ -950,8 +950,20 @@ class HomeWidgetService {_progressTimer = null;}+ void _ensureStatsTimer() {+ if (_statsTimer?.isActive == true) return;+ _statsTimer = Timer.periodic(_statsThrottle, (_) => refreshStats());+ }+void onAppBackgrounded() {_stopProgressTimer();+ // Stop polling stats while backgrounded-and-paused - nothing is accruing.+ // Keep it running if we're still playing so the widget's "today" total+ // keeps ticking during long background listening sessions.+ if (!AudioPlayerService().isPlaying) {+ _statsTimer?.cancel();+ _statsTimer = null;+ }}void onAppForegrounded() {@@ -959,6 +971,7 @@ class HomeWidgetService {_startProgressTimer();_scheduleUpdate();}+ _ensureStatsTimer();refreshStats();}}diff --git a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.javaindex cad8ff3d..9201e57d 100644--- a/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java+++ b/packages/audio_service/android/src/main/java/com/ryanheise/audioservice/AudioService.java@@ -722,6 +722,13 @@ public class AudioService extends MediaBrowserServiceCompat {private void exitPlayingState() {if (config.androidStopForegroundOnPause) {exitForegroundState();+ } else {+ // Keep the foreground service alive so the notification, lock+ // screen, Bluetooth and WearOS controls stay responsive after a+ // pause, but release the CPU wakelock - holding PARTIAL_WAKE_LOCK+ // while paused drains battery for nothing. enterPlayingState()+ // re-acquires it on resume.+ releaseWakeLock();}}diff --git a/packages/just_audio/lib/just_audio.dart b/packages/just_audio/lib/just_audio.dartindex 0aa64da4..ed234c06 100644--- a/packages/just_audio/lib/just_audio.dart+++ b/packages/just_audio/lib/just_audio.dart@@ -678,11 +678,13 @@ class AudioPlayer {Timer? currentTimer;StreamSubscription<Duration?>? durationSubscription;StreamSubscription<PlaybackEvent>? playbackEventSubscription;+ StreamSubscription<bool>? playingSubscription;void yieldPosition(Timer timer) {if (controller.isClosed || _durationSubject.isClosed) {timer.cancel();durationSubscription?.cancel();playbackEventSubscription?.cancel();+ playingSubscription?.cancel();if (!controller.isClosed) {// This will in turn close _positionSubject.controller.close();@@ -694,9 +696,20 @@ class AudioPlayer {}}- durationSubscription = durationStream.listen((duration) {+ // Only run the periodic timer while actually playing. While paused or+ // stopped it would otherwise keep waking the event loop (and, under a held+ // wakelock, the CPU) ~once a second forever. Seeks while paused still+ // update the position via the playbackEventStream listener below.+ void restartTimer() {currentTimer?.cancel();- currentTimer = Timer.periodic(step(), yieldPosition);+ currentTimer = playing ? Timer.periodic(step(), yieldPosition) : null;+ }++ durationSubscription = durationStream.listen((duration) {+ restartTimer();+ }, onError: (Object e, StackTrace stackTrace) {});+ playingSubscription = playingStream.listen((_) {+ restartTimer();}, onError: (Object e, StackTrace stackTrace) {});playbackEventSubscription = playbackEventStream.listen((event) {controller.add(position);