Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Battery optimizations, Android Auto phantom play fix, UI scaling fixes

Nathan Poulson57c9ecae5b81
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index e309d25d..83724a72 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -618,14 +618,16 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
// ── Battery-saving lifecycle ──
void onAppBackgrounded() {
+ debugPrint('[BG-AUDIT] LibraryProvider.onAppBackgrounded() playing=${AudioPlayerService().isPlaying}');
_isBackgrounded = true;
_stopServerPingTimer();
- if (!AudioPlayerService().isPlaying && !ChromecastService().isPlaying) {
- _softDisconnectSocket();
- }
+ _idleDisconnectTimer?.cancel(); // No timers in background
+ _idleDisconnectTimer = null;
+ _softDisconnectSocket(); // Always disconnect, even during playback
}
void onAppForegrounded() {
+ debugPrint('[BG-AUDIT] LibraryProvider.onAppForegrounded()');
_isBackgrounded = false;
_softReconnectSocket();
if (_networkOffline && _deviceHasConnectivity && !_manualOffline) {
@@ -638,25 +640,34 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
_idleDisconnectTimer?.cancel();
_idleDisconnectTimer = Timer(_StateMixin._idleTimeout, () {
if (!AudioPlayerService().isPlaying && !ChromecastService().isPlaying) {
- debugPrint('[Library] Idle timeout - soft disconnecting socket');
+ debugPrint('[BG-AUDIT] idleTimer disconnecting socket');
_softDisconnectSocket();
}
});
}
void onPlaybackStarted() {
- _softReconnectSocket();
+ debugPrint('[BG-AUDIT] LibraryProvider.onPlaybackStarted() bg=$_isBackgrounded');
+ if (!_isBackgrounded) {
+ debugPrint('[BG-AUDIT] socket reconnect (foreground playback start)');
+ _softReconnectSocket();
+ } else {
+ debugPrint('[BG-AUDIT] socket reconnect SKIPPED (backgrounded)');
+ }
_idleDisconnectTimer?.cancel();
}
void onPlaybackStopped() {
- _restartIdleTimer();
+ debugPrint('[BG-AUDIT] LibraryProvider.onPlaybackStopped() bg=$_isBackgrounded');
if (_isBackgrounded) {
_softDisconnectSocket();
+ } else {
+ _restartIdleTimer();
}
}
void _softDisconnectSocket() {
+ debugPrint('[BG-AUDIT] _softDisconnectSocket() alreadyDisconnected=$_socketSoftDisconnected manualOffline=$_manualOffline');
if (_socketSoftDisconnected || _manualOffline) return;
_socketSoftDisconnected = true;
SocketService().softDisconnect();
@@ -1613,7 +1624,11 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
}
void _checkRollingDownloads(String playingKey) async {
- if (_api == null || isOffline || _rollingDownloadSeries.isEmpty) return;
+ debugPrint('[BG-AUDIT] _checkRollingDownloads key=$playingKey api=${_api != null} offline=$isOffline series=${_rollingDownloadSeries.length}');
+ if (_api == null || isOffline || _rollingDownloadSeries.isEmpty) {
+ debugPrint('[BG-AUDIT] _checkRollingDownloads BAILED early');
+ return;
+ }
final count = await PlayerSettings.getRollingDownloadCount();
if (playingKey.length > 36) {
@@ -1637,12 +1652,19 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
}
void _checkQueueAutoDownloads(String playingKey) async {
- if (_api == null || isOffline) return;
+ debugPrint('[BG-AUDIT] _checkQueueAutoDownloads key=$playingKey');
+ if (_api == null || isOffline) {
+ debugPrint('[BG-AUDIT] _checkQueueAutoDownloads BAILED (api/offline)');
+ return;
+ }
final isPodcastKey = playingKey.length > 36;
final queueMode = isPodcastKey
? await PlayerSettings.getPodcastQueueMode()
: await PlayerSettings.getBookQueueMode();
- if (queueMode != 'manual') return;
+ if (queueMode != 'manual') {
+ debugPrint('[BG-AUDIT] _checkQueueAutoDownloads BAILED (queueMode=$queueMode)');
+ return;
+ }
final enabled = await PlayerSettings.getQueueAutoDownload();
if (!enabled) return;
final merged = await PlayerSettings.getMergeAbsorbingLibraries();
@@ -1728,9 +1750,16 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
}
void _checkAutoDownloadOnStream(String playingKey) async {
- if (_api == null || isOffline) return;
+ debugPrint('[BG-AUDIT] _checkAutoDownloadOnStream key=$playingKey');
+ if (_api == null || isOffline) {
+ debugPrint('[BG-AUDIT] _checkAutoDownloadOnStream BAILED (api/offline)');
+ return;
+ }
final enabled = await PlayerSettings.getAutoDownloadOnStream();
- if (!enabled) return;
+ if (!enabled) {
+ debugPrint('[BG-AUDIT] _checkAutoDownloadOnStream BAILED (disabled)');
+ return;
+ }
final connectivity = await Connectivity().checkConnectivity();
if (!connectivity.contains(ConnectivityResult.wifi)) return;
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 3f56c599..bc906542 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -72,12 +72,19 @@ class LibraryProvider extends ChangeNotifier
AudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);
AudioPlayerService.setOnPlayStartedCallback((key) {
- _checkRollingDownloads(key);
- Future.delayed(const Duration(seconds: 2),
- () => _checkQueueAutoDownloads(key));
- _checkAutoDownloadOnStream(key);
+ debugPrint('[BG-AUDIT] onPlayStarted key=$key - deferring download checks 30s');
+ // Defer download checks to avoid a network burst at playback start.
+ Future.delayed(const Duration(seconds: 30), () {
+ final stillPlaying = AudioPlayerService().isPlaying;
+ debugPrint('[BG-AUDIT] deferred download checks firing: stillPlaying=$stillPlaying');
+ if (!stillPlaying) return;
+ _checkRollingDownloads(key);
+ _checkQueueAutoDownloads(key);
+ _checkAutoDownloadOnStream(key);
+ });
});
AudioPlayerService.setOnPlaybackStateChangedCallback((playing) {
+ debugPrint('[BG-AUDIT] onPlaybackStateChanged playing=$playing');
if (playing) {
onPlaybackStarted();
} else {
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index 7cd899fe..d1758ae1 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -6,6 +6,7 @@ import 'package:provider/provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
import '../services/chromecast_service.dart';
+import '../services/home_widget_service.dart';
import '../services/sleep_timer_service.dart';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
@@ -393,10 +394,12 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
+ debugPrint('[BG-AUDIT] AppShell lifecycle: $state');
if (state == AppLifecycleState.resumed) {
context.read<LibraryProvider>().onAppForegrounded();
SleepTimerService().onAppForegrounded();
AudioPlayerService.onAppForegrounded();
+ HomeWidgetService().onAppForegrounded();
_refreshDataForTab(_currentIndex);
// Check auto sleep in case we resumed into the window
SleepTimerService().checkAutoSleep();
@@ -404,6 +407,8 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
} 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();
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 35d43b52..f20fb1c9 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -710,9 +710,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
SizedBox(height: 4),
Text('Your absorbing cards act as a playlist. When one finishes, the next non-finished card auto-plays. Add items with the "Add to Absorbing" button on a book or episode and reorder from the absorbing screen.'),
SizedBox(height: 12),
- Text('Auto Absorb', style: TextStyle(fontWeight: FontWeight.w600)),
+ Text('Series', style: TextStyle(fontWeight: FontWeight.w600)),
SizedBox(height: 4),
- Text('Automatically absorbs the next book in a series or the next episode in a podcast show.'),
+ Text('Automatically plays the next book in a series or the next episode in a podcast show.'),
],
),
actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: Text('Got it'))],
@@ -730,9 +730,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
SizedBox(width: double.infinity, child: SegmentedButton<String>(
showSelectedIcon: false,
segments: const [
- ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
- ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
- ButtonSegment(value: 'auto_next', icon: Icon(Icons.skip_next_rounded), label: Text('Auto')),
+ ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text('Off'))),
+ ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text('Manual'))),
+ ButtonSegment(value: 'auto_next', icon: Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text('Series'))),
],
selected: {_mergedQueueMode},
onSelectionChanged: _loaded ? (s) {
@@ -753,9 +753,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
SizedBox(width: double.infinity, child: SegmentedButton<String>(
showSelectedIcon: false,
segments: const [
- ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
- ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
- ButtonSegment(value: 'auto_next', icon: Icon(Icons.skip_next_rounded), label: Text('Auto')),
+ ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text('Off'))),
+ ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text('Manual'))),
+ ButtonSegment(value: 'auto_next', icon: Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text('Series'))),
],
selected: {_bookQueueMode},
onSelectionChanged: _loaded ? (s) {
@@ -1080,9 +1080,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
child: SegmentedButton<String>(
showSelectedIcon: false,
segments: const [
- ButtonSegment(value: 'off', label: Text('Off')),
- ButtonSegment(value: 'addTime', label: Text('Add Time')),
- ButtonSegment(value: 'resetTimer', label: Text('Reset')),
+ ButtonSegment(value: 'off', label: FittedBox(fit: BoxFit.scaleDown, child: Text('Off'))),
+ ButtonSegment(value: 'addTime', label: FittedBox(fit: BoxFit.scaleDown, child: Text('Add Time'))),
+ ButtonSegment(value: 'resetTimer', label: FittedBox(fit: BoxFit.scaleDown, child: Text('Reset'))),
],
selected: {_shakeMode},
onSelectionChanged: _loaded ? (v) {
@@ -1420,10 +1420,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
SizedBox(width: double.infinity, child: SegmentedButton<int>(
showSelectedIcon: false,
segments: const [
- ButtonSegment(value: 0, label: Text('Off')),
- ButtonSegment(value: 128, label: Text('128 MB')),
- ButtonSegment(value: 256, label: Text('256 MB')),
- ButtonSegment(value: 512, label: Text('512 MB')),
+ ButtonSegment(value: 0, label: FittedBox(fit: BoxFit.scaleDown, child: Text('Off'))),
+ ButtonSegment(value: 128, label: FittedBox(fit: BoxFit.scaleDown, child: Text('128 MB'))),
+ ButtonSegment(value: 256, label: FittedBox(fit: BoxFit.scaleDown, child: Text('256 MB'))),
+ ButtonSegment(value: 512, label: FittedBox(fit: BoxFit.scaleDown, child: Text('512 MB'))),
],
selected: {_streamingCacheSizeMb},
onSelectionChanged: (v) {
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 8030c08a..4fed89d2 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -23,6 +23,11 @@ export 'player_settings.dart';
class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
final AudioPlayer _player = AudioPlayer(
handleInterruptions: false,
+ // Android: bypass the local HTTP proxy for auth headers — ExoPlayer
+ // supports headers natively via DefaultHttpDataSource, so the proxy
+ // just doubles the packet count for no benefit.
+ // iOS: keep the proxy — AVPlayer can't set custom headers natively.
+ useProxyForRequestHeaders: !Platform.isAndroid,
audioLoadConfiguration: const AudioLoadConfiguration(
androidLoadControl: AndroidLoadControl(
bufferForPlaybackDuration: Duration(milliseconds: 500),
@@ -306,7 +311,7 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
Timer? _clickTimer;
int _clickCount = 0;
DateTime? _hardwareButtonTime; // cooldown after hardware next/prev
- bool _noisyPauseFlag = false; // suppress click resolution after BT disconnect
+ DateTime? _noisyPauseAt; // suppress clicks for a window after BT disconnect
@override
Future<void> click([MediaButton button = MediaButton.media]) async {
@@ -336,17 +341,21 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
_hardwareButtonTime = null;
}
+ // Suppress phantom play commands within 5s of a BT/auto disconnect
+ if (_noisyPauseAt != null) {
+ final elapsed = DateTime.now().difference(_noisyPauseAt!).inMilliseconds;
+ if (elapsed < 5000) {
+ debugPrint('[Handler] Ignoring phantom click (${elapsed}ms after noisy pause)');
+ return;
+ }
+ _noisyPauseAt = null;
+ }
+
_clickCount++;
_clickTimer?.cancel();
- _noisyPauseFlag = false;
_clickTimer = Timer(const Duration(milliseconds: 400), () async {
final count = _clickCount;
_clickCount = 0;
- if (_noisyPauseFlag) {
- debugPrint('[Handler] click resolved: count=$count — suppressed (noisy pause)');
- _noisyPauseFlag = false;
- return;
- }
debugPrint('[Handler] click resolved: count=$count playing=${_player.playing}');
switch (count) {
case 1:
@@ -374,7 +383,7 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
/// Cancel any pending media-button click so a BT disconnect doesn't
/// accidentally resume playback on the phone speaker.
void cancelPendingClick() {
- _noisyPauseFlag = true;
+ _noisyPauseAt = DateTime.now();
if (_clickTimer?.isActive ?? false) {
debugPrint('[Handler] Cancelling pending click (noisy pause)');
_clickTimer!.cancel();
@@ -678,6 +687,9 @@ class AudioPlayerService extends ChangeNotifier {
ApiService? get currentApi => _api;
String? _playbackSessionId;
bool _isOfflineMode = false;
+ bool _isBackgrounded = false;
+ bool get isBackgrounded => _isBackgrounded;
+ SharedPreferences? _prefs;
StreamSubscription? _syncSub;
StreamSubscription? _completionSub;
Timer? _bgSaveTimer;
@@ -1108,10 +1120,29 @@ class AudioPlayerService extends ChangeNotifier {
/// 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 void onAppBackgrounded() {
+ debugPrint('[BG-AUDIT] AudioPlayerService.onAppBackgrounded() playing=${_instance.isPlaying}');
+ _instance._isBackgrounded = true;
+ }
+
static Future<void> onAppForegrounded() async {
final service = _instance;
+ service._isBackgrounded = false;
if (!service.hasBook) return;
+ debugPrint('[BG-AUDIT] AudioPlayerService.onAppForegrounded() playing=${service.isPlaying}');
debugPrint('[MediaSession] Foregrounded - refreshing (playing=${service.isPlaying}, session=${service._playbackSessionId != null}, item=${service._currentItemId})');
+ // Flush missed UI updates from background
+ debugPrint('[BG-AUDIT] notifyListeners() flush on foreground');
+ service.notifyListeners();
+ // Flush overdue server sync
+ if (service.isPlaying && service._currentItemId != null) {
+ final sinceSync = DateTime.now().difference(service._lastServerSync).inSeconds;
+ debugPrint('[BG-AUDIT] foreground sync check: sinceLastSync=${sinceSync}s');
+ if (sinceSync > 60) {
+ debugPrint('[BG-AUDIT] foreground sync FLUSHING overdue sync');
+ service._syncToServer(service.position);
+ }
+ }
// Re-activate audio session to get a fresh system token
try { (await AudioSession.instance).setActive(true); } catch (_) {}
// Re-push playback state so the system re-registers the MediaSession
@@ -1892,6 +1923,13 @@ class AudioPlayerService extends ChangeNotifier {
}
int _lastSyncSecond = -1;
+ int _lastBgProcessedSec = -1;
+ // BG-AUDIT counters - compile per-second summaries instead of per-tick logs
+ int _auditTickCount = 0;
+ int _auditSkippedTicks = 0;
+ int _auditLastReportSec = -1;
+ int _auditNotifyCount = 0;
+ int _auditNotifySkipped = 0;
StreamSubscription? _eqSessionSub;
@@ -1934,23 +1972,27 @@ class AudioPlayerService extends ChangeNotifier {
_completionSub?.cancel();
_bgSaveTimer?.cancel();
_lastSyncSecond = -1;
+ _lastBgProcessedSec = -1;
_lastChapterCheckSec = -1;
_lastKnownPositionSec = 0;
_lastServerSync = DateTime.now();
+ // Cache prefs in background - not needed synchronously here
+ if (_prefs == null) {
+ SharedPreferences.getInstance().then((p) => _prefs = p);
+ }
// Safety-net timer for position persistence when Android throttles the
// Dart position stream in the background. The primary positionStream
// listener saves every 5s; this only matters when that stream goes silent.
- _bgSaveTimer = Timer.periodic(const Duration(seconds: 60), (_) async {
+ _bgSaveTimer = Timer.periodic(const Duration(seconds: 300), (_) async {
+ debugPrint('[BG-AUDIT] bgSaveTimer FIRED bg=$_isBackgrounded');
if (_currentItemId == null || _player == null || !_player!.playing) return;
final pos = position;
final posSec = pos.inMilliseconds / 1000.0;
if (posSec <= 0) return;
+ debugPrint('[BG-AUDIT] bgSaveTimer saving pos=${posSec.toStringAsFixed(1)}s');
await _saveProgressLocal(pos);
- // Server sync is handled by the positionStream listener every 60s.
- // This timer only does local saves as a safety net for when Android
- // throttles the position stream in the background.
});
// Attach equalizer to current audio session
@@ -1961,12 +2003,17 @@ class AudioPlayerService extends ChangeNotifier {
// position-reset can confuse the position-based detection.
_completionSub = _player?.processingStateStream.listen((state) {
if (state == ProcessingState.completed && _currentItemId != null) {
- debugPrint('[Player] processingState → completed');
+ debugPrint('[BG-AUDIT] processingState=completed');
_onPlaybackComplete();
}
- // Notify UI when buffering/loading state changes so spinners update
- if (state == ProcessingState.ready || state == ProcessingState.loading || state == ProcessingState.buffering) {
+ // Notify UI when buffering/loading state changes so spinners update.
+ // Skip when backgrounded - no visible UI to rebuild; flushed on foreground.
+ if (!_isBackgrounded &&
+ (state == ProcessingState.ready || state == ProcessingState.loading || state == ProcessingState.buffering)) {
+ _auditNotifyCount++;
notifyListeners();
+ } else if (_isBackgrounded) {
+ _auditNotifySkipped++;
}
}, onError: (Object e, StackTrace st) {
debugPrint('[Player] processingState stream error: $e');
@@ -1997,6 +2044,25 @@ class AudioPlayerService extends ChangeNotifier {
if (sec <= 0) return;
+ _auditTickCount++;
+ // In background, only process once per second to save CPU.
+ if (_isBackgrounded) {
+ if (sec == _lastBgProcessedSec) {
+ _auditSkippedTicks++;
+ return;
+ }
+ _lastBgProcessedSec = sec;
+ }
+ // Log a compiled summary every 5 seconds
+ if (sec % 5 == 0 && sec != _auditLastReportSec) {
+ _auditLastReportSec = sec;
+ debugPrint('[BG-AUDIT] positionStream 5s summary: ticks=$_auditTickCount skipped=$_auditSkippedTicks processed=${_auditTickCount - _auditSkippedTicks} notifyListeners=$_auditNotifyCount notifySkipped=$_auditNotifySkipped bg=$_isBackgrounded pos=${posSec.toStringAsFixed(1)}s');
+ _auditTickCount = 0;
+ _auditSkippedTicks = 0;
+ _auditNotifyCount = 0;
+ _auditNotifySkipped = 0;
+ }
+
// ─── Chapter change detection ──────────────────────────
// Update notification subtitle when the chapter changes.
// Throttled to once per second — chapters can't change faster than that.
@@ -2062,29 +2128,36 @@ class AudioPlayerService extends ChangeNotifier {
// Save locally every 5 seconds (always works, even offline)
if (sec % 5 == 0 && sec != _lastSyncSecond && _currentItemId != null) {
_lastSyncSecond = sec;
+ debugPrint('[BG-AUDIT] localSave pos=${posSec.toStringAsFixed(1)}s bg=$_isBackgrounded');
_saveProgressLocal(absolutePos);
- // Also sync to server every 60 seconds (unless manual offline)
- if (sec % 60 == 0) {
- final prefs = await SharedPreferences.getInstance();
- final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ // Sync to server: 60s foreground, 300s background
+ final syncInterval = _isBackgrounded ? 300 : 60;
+ final sinceLastSync = DateTime.now().difference(_lastServerSync).inSeconds;
+ if (sinceLastSync >= syncInterval) {
+ debugPrint('[BG-AUDIT] serverSync FIRING interval=${syncInterval}s sinceLastSync=${sinceLastSync}s bg=$_isBackgrounded');
+ final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
+ .getBool('manual_offline_mode') ?? false;
if (manualOffline || _isOfflineMode || _playbackSessionId == null) {
// Offline or no session - accumulate listening time locally
final progressKey = _currentEpisodeId != null
? '$_currentItemId-$_currentEpisodeId'
: _currentItemId!;
- _progressSync.addOfflineListeningTime(progressKey, 60);
+ debugPrint('[BG-AUDIT] offlineAccumulate key=$progressKey secs=${sinceLastSync.clamp(0, 300)}');
+ _progressSync.addOfflineListeningTime(progressKey, sinceLastSync.clamp(0, 300));
}
if (manualOffline) {
+ debugPrint('[BG-AUDIT] serverSync SKIPPED (manualOffline)');
// Manual offline — local save only, no server sync
} else if (!_isOfflineMode && _playbackSessionId != null) {
// Streaming/local with session: sync via session
+ debugPrint('[BG-AUDIT] serverSync SESSION pos=${absolutePos.inSeconds}s');
_syncToServer(absolutePos);
} else if (!_isOfflineMode && _api != null && _currentItemId != null) {
// No session but online — sync via progress update endpoint
- debugPrint('[Player] No-session sync — sending to server at ${absolutePos.inSeconds}s');
+ debugPrint('[BG-AUDIT] serverSync NO-SESSION pos=${absolutePos.inSeconds}s');
try {
final syncKey = _currentEpisodeId != null
? '$_currentItemId-$_currentEpisodeId'
@@ -2406,6 +2479,7 @@ class AudioPlayerService extends ChangeNotifier {
_pauseStopTimer?.cancel();
_pauseStopTimer = null;
_noisyPause = false; // User explicitly resumed — allow interrupt-resume again
+ _handler?._noisyPauseAt = null; // Clear noisy suppression window
// Auto-rewind on resume if enabled
if (_lastPauseTime != null && _player != null) {
final settings = await AutoRewindSettings.load();
@@ -2445,8 +2519,8 @@ class AudioPlayerService extends ChangeNotifier {
// Re-create server session if it was closed (e.g. pause timeout)
// and check if server progress is ahead (e.g. user listened on another client)
if (_api != null && _currentItemId != null) {
- final prefs = await SharedPreferences.getInstance();
- final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
+ .getBool('manual_offline_mode') ?? false;
if (manualOffline || _isOfflineMode) {
debugPrint('[Player] Skipping session re-create on resume (manualOffline=$manualOffline, isOffline=$_isOfflineMode)');
} else {
@@ -2506,17 +2580,21 @@ class AudioPlayerService extends ChangeNotifier {
return;
}
_player?.play();
+ debugPrint('[BG-AUDIT] play() bg=$_isBackgrounded');
_logEvent(PlaybackEventType.play);
_onPlaybackStateChangedCallback?.call(true);
// Restart safety-net save timer (stopped on pause to avoid background wakes)
if (_bgSaveTimer == null || !_bgSaveTimer!.isActive) {
+ debugPrint('[BG-AUDIT] bgSaveTimer RESTARTED (300s)');
_bgSaveTimer?.cancel();
- _bgSaveTimer = Timer.periodic(const Duration(seconds: 60), (_) async {
+ _bgSaveTimer = Timer.periodic(const Duration(seconds: 300), (_) async {
+ debugPrint('[BG-AUDIT] bgSaveTimer FIRED (play-restart) bg=$_isBackgrounded');
if (_currentItemId == null || _player == null || !_player!.playing) return;
final pos = position;
final posSec = pos.inMilliseconds / 1000.0;
if (posSec <= 0) return;
+ debugPrint('[BG-AUDIT] bgSaveTimer saving pos=${posSec.toStringAsFixed(1)}s');
await _saveProgressLocal(pos);
});
}
@@ -2533,6 +2611,7 @@ class AudioPlayerService extends ChangeNotifier {
}
Future<void> pause() async {
+ debugPrint('[BG-AUDIT] pause() bg=$_isBackgrounded');
debugPrint('[Service] pause() called');
_playVerifyTimer?.cancel();
_wasPlayingBeforeInterrupt = false;
@@ -2556,8 +2635,8 @@ class AudioPlayerService extends ChangeNotifier {
await _saveProgressLocal(pos);
// Check manual offline before syncing
- final prefs = await SharedPreferences.getInstance();
- final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
+ .getBool('manual_offline_mode') ?? false;
if (manualOffline) return;
if (!_isOfflineMode && _playbackSessionId != null) {
@@ -2745,8 +2824,8 @@ class AudioPlayerService extends ChangeNotifier {
}
// Check manual offline before syncing
- final prefs = await SharedPreferences.getInstance();
- final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
+ .getBool('manual_offline_mode') ?? false;
if (!manualOffline) {
// Try server sync
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index cfd3b7eb..7fe24c29 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -22,6 +22,8 @@ class HomeWidgetService {
Timer? _progressTimer;
Timer? _pendingUpdate;
+ int _auditPlayerChangedCount = 0;
+ int _auditThrottledCount = 0;
String? _lastCoverItemId;
DateTime? _lastUpdate;
bool _initialized = false;
@@ -158,11 +160,13 @@ class HomeWidgetService {
}
void _onPlayerChanged() {
+ _auditPlayerChangedCount++;
// Throttle to max once per 2 seconds, but never drop an update —
// schedule a deferred one so the final state always gets pushed.
final now = DateTime.now();
if (_lastUpdate != null &&
now.difference(_lastUpdate!).inMilliseconds < 2000) {
+ _auditThrottledCount++;
_pendingUpdate?.cancel();
_pendingUpdate = Timer(const Duration(seconds: 2), _scheduleUpdate);
return;
@@ -173,6 +177,7 @@ class HomeWidgetService {
/// Schedule an update on the next microtask so we never do async work
/// inside the synchronous ChangeNotifier callback.
void _scheduleUpdate() {
+ debugPrint('[BG-AUDIT] HomeWidget._scheduleUpdate() updating=$_updating');
if (_updating) return;
_updating = true;
Future.microtask(() async {
@@ -187,6 +192,9 @@ class HomeWidgetService {
}
Future<void> _updateWidgetData() async {
+ debugPrint('[BG-AUDIT] HomeWidget._updateWidgetData() playerChangedSinceLastUpdate=$_auditPlayerChangedCount throttled=$_auditThrottledCount');
+ _auditPlayerChangedCount = 0;
+ _auditThrottledCount = 0;
_lastUpdate = DateTime.now();
final player = AudioPlayerService();
final hasBook = player.hasBook;
@@ -265,6 +273,7 @@ class HomeWidgetService {
// If no local cover, download from server to a temp file.
if (coverPath == null) {
if (coverUrl != null && coverUrl.isNotEmpty) {
+ debugPrint('[BG-AUDIT] HomeWidget._updateCoverArt HTTP FETCH $coverUrl');
final cacheDir = await getTemporaryDirectory();
final widgetCoverDir = Directory('${cacheDir.path}/widget_covers');
if (!widgetCoverDir.existsSync()) {
@@ -296,13 +305,29 @@ class HomeWidgetService {
void _startProgressTimer() {
if (_progressTimer?.isActive == true) return;
+ debugPrint('[BG-AUDIT] HomeWidget._startProgressTimer (120s)');
_progressTimer = Timer.periodic(const Duration(seconds: 120), (_) {
+ debugPrint('[BG-AUDIT] HomeWidget progressTimer FIRED');
_scheduleUpdate();
});
}
void _stopProgressTimer() {
+ debugPrint('[BG-AUDIT] HomeWidget._stopProgressTimer');
_progressTimer?.cancel();
_progressTimer = null;
}
+
+ void onAppBackgrounded() {
+ debugPrint('[BG-AUDIT] HomeWidget.onAppBackgrounded()');
+ _stopProgressTimer();
+ }
+
+ void onAppForegrounded() {
+ debugPrint('[BG-AUDIT] HomeWidget.onAppForegrounded() playing=${AudioPlayerService().isPlaying}');
+ if (AudioPlayerService().isPlaying) {
+ _startProgressTimer();
+ _scheduleUpdate();
+ }
+ }
}
diff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dart
index dfd57d68..a2e3f2bf 100644
--- a/lib/services/progress_sync_service.dart
+++ b/lib/services/progress_sync_service.dart
@@ -29,8 +29,9 @@ class ProgressSyncService {
_connectivitySub = Connectivity().onConnectivityChanged.listen((result) {
final wasOffline = !_isOnline;
_isOnline = !result.contains(ConnectivityResult.none);
+ debugPrint('[BG-AUDIT] ProgressSync connectivity changed: online=$_isOnline wasOffline=$wasOffline');
if (_isOnline && wasOffline) {
- debugPrint('[Sync] Back online - flushing pending syncs');
+ debugPrint('[BG-AUDIT] ProgressSync back online - flushing pending syncs');
_consecutiveFailures = 0; // reset backoff on connectivity change
flushPendingSync();
}
@@ -178,6 +179,7 @@ class ProgressSyncService {
/// Flush all pending syncs (call when coming back online).
/// Compares local vs server timestamps — last-write-wins.
Future<void> flushPendingSync({ApiService? api, int maxItems = 5}) async {
+ debugPrint('[BG-AUDIT] flushPendingSync online=$_isOnline api=${api != null}');
if (!_isOnline || api == null) return;
if (_isFlushing) {
diff --git a/lib/widgets/tips_sheet.dart b/lib/widgets/tips_sheet.dart
index e4b88a31..f3f52c16 100644
--- a/lib/widgets/tips_sheet.dart
+++ b/lib/widgets/tips_sheet.dart
@@ -32,6 +32,11 @@ void showTipsSheet(BuildContext context) {
title: 'Quick Bookmarks',
desc: 'Long-press the bookmark button on any card to instantly drop a bookmark at your current position without opening the bookmark sheet.',
),
+ _tipCard(cs, tt,
+ icon: Icons.edit_note_rounded,
+ title: 'Edit Bookmarks',
+ desc: 'Long-press any bookmark in the bookmark sheet to edit its title and add notes.',
+ ),
_tipCard(cs, tt,
icon: Icons.touch_app_rounded,
title: 'Cover Play/Pause',
@@ -47,11 +52,6 @@ void showTipsSheet(BuildContext context) {
title: 'Quick Add to Absorbing',
desc: 'Swipe right on any book in a list sheet (series, author, search results) to instantly add it to your absorbing queue.',
),
- _tipCard(cs, tt,
- icon: Icons.edit_note_rounded,
- title: 'Edit Bookmarks',
- desc: 'Long-press any bookmark in the bookmark sheet to edit its title and add notes.',
- ),
_tipCard(cs, tt,
icon: Icons.vibration_rounded,
title: 'Shake to Extend Sleep',
@@ -89,8 +89,8 @@ void showTipsSheet(BuildContext context) {
),
_tipCard(cs, tt,
icon: Icons.skip_next_rounded,
- title: 'Queue Mode',
- desc: 'When you finish a book that\'s part of a series, Absorb can automatically queue up the next book. Enable this in Settings under Absorbing Cards.',
+ title: 'Series Queue Mode',
+ desc: 'When you finish a book that\'s part of a series, Absorb can automatically play the next book. Set queue mode to "Series" in Settings.',
),
_tipCard(cs, tt,
icon: Icons.airplanemode_active_rounded,
diff --git a/lib/widgets/welcome_sheet.dart b/lib/widgets/welcome_sheet.dart
index 4fa61cdc..7cb955d4 100644
--- a/lib/widgets/welcome_sheet.dart
+++ b/lib/widgets/welcome_sheet.dart
@@ -55,7 +55,8 @@ class _WelcomeContent extends StatelessWidget {
),
Flexible(
child: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(24, 20, 24, 32),
+ padding: EdgeInsets.fromLTRB(24, 20, 24,
+ 32 + MediaQuery.of(context).viewPadding.bottom),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -106,7 +107,7 @@ class _WelcomeContent extends StatelessWidget {
items: [
'Off - playback stops when a book finishes',
'Manual - auto-plays the next card in your queue',
- 'Auto Absorb - automatically finds and plays the next book in a series',
+ 'Series - automatically finds and plays the next book in a series',
],
),
diff --git a/pubspec.yaml b/pubspec.yaml
index f90e7f65..566dc569 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.8.63+80
+version: 1.8.64+81
# v1.8.41: JWT auth (accessToken + refreshToken), MANAGE_EXTERNAL_STORAGE removed from playstore flavor
# Build scripts (run from Git Bash):
# . ./build_bundle.sh - Play Store AAB (no MANAGE_EXTERNAL_STORAGE)