Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Battery saving: disconnect socket when backgrounded/idle, kill ping timer

Nathan Poulson17be78274f6b
diff --git a/lib/main.dart b/lib/main.dart
index da7f93e5..fe08ee8f 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -34,6 +34,9 @@ final ValueNotifier<ThemeMode> themeNotifier = ValueNotifier(ThemeMode.dark);
/// Whether OLED (pure black) dark theme is active.
final ValueNotifier<bool> oledNotifier = ValueNotifier(false);
+/// Whether to use instant page transitions instead of slide animations.
+final ValueNotifier<bool> snappyTransitionsNotifier = ValueNotifier(false);
+
/// Global key so non-widget code (e.g. providers) can show snackbars.
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
@@ -74,6 +77,7 @@ void main() async {
try {
final savedTheme = await PlayerSettings.getThemeMode();
applyThemeMode(savedTheme);
+ snappyTransitionsNotifier.value = await PlayerSettings.getSnappyTransitions();
} catch (_) {}
// Capture Flutter framework errors (widget build failures, etc.)
@@ -130,6 +134,9 @@ class AbsorbApp extends StatelessWidget {
systemNavigationBarIconBrightness: isDark ? Brightness.light : Brightness.dark,
));
+ return ValueListenableBuilder<bool>(
+ valueListenable: snappyTransitionsNotifier,
+ builder: (context, snappy, _) {
return DynamicColorBuilder(
builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
// Absorb is dark-first — use dynamic dark colors or our custom palette
@@ -166,13 +173,16 @@ class AbsorbApp extends StatelessWidget {
);
}
- // Smooth page transition theme
- const pageTransition = PageTransitionsTheme(
- builders: {
- TargetPlatform.android: CupertinoPageTransitionsBuilder(),
- TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
- },
- );
+ // Page transition theme
+ final pageTransition = snappy
+ ? const PageTransitionsTheme(builders: {
+ TargetPlatform.android: _InstantPageTransitionsBuilder(),
+ TargetPlatform.iOS: _InstantPageTransitionsBuilder(),
+ })
+ : const PageTransitionsTheme(builders: {
+ TargetPlatform.android: CupertinoPageTransitionsBuilder(),
+ TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
+ });
return MaterialApp(
scaffoldMessengerKey: scaffoldMessengerKey,
@@ -295,11 +305,27 @@ class AbsorbApp extends StatelessWidget {
);
},
);
+ },
+ );
},
);
}
}
+/// Instant page transitions (no animation) for snappy mode.
+class _InstantPageTransitionsBuilder extends PageTransitionsBuilder {
+ const _InstantPageTransitionsBuilder();
+
+ @override
+ Widget buildTransitions<T>(
+ PageRoute<T> route,
+ BuildContext context,
+ Animation<double> animation,
+ Animation<double> secondaryAnimation,
+ Widget child,
+ ) => child;
+}
+
class AuthGate extends StatefulWidget {
const AuthGate({super.key});
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index ed23d007..57bc2d81 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -105,6 +105,12 @@ class LibraryProvider extends ChangeNotifier {
bool get isOffline => _manualOffline || _networkOffline;
bool get isManualOffline => _manualOffline;
+ // Battery-saving: soft-disconnect socket when idle or backgrounded
+ bool _isBackgrounded = false;
+ bool _socketSoftDisconnected = false;
+ Timer? _idleDisconnectTimer;
+ static const _idleTimeout = Duration(minutes: 5);
+
/// Toggle manual offline mode.
Future<void> setManualOffline(bool value) async {
debugPrint('[Library] setManualOffline($value)');
@@ -442,6 +448,13 @@ class LibraryProvider extends ChangeNotifier {
_checkRollingDownloads(key);
_checkQueueAutoDownloads(key);
});
+ AudioPlayerService.setOnPlaybackStateChangedCallback((playing) {
+ if (playing) {
+ onPlaybackStarted();
+ } else {
+ onPlaybackStopped();
+ }
+ });
ChromecastService.setOnBookFinishedCallback(markFinishedLocally);
restoreOfflineMode().then((_) async {
@@ -489,7 +502,10 @@ class LibraryProvider extends ChangeNotifier {
_lastAuthKey = null;
AudioPlayerService.setOnBookFinishedCallback(null);
AudioPlayerService.setOnPlayStartedCallback(null);
+ AudioPlayerService.setOnPlaybackStateChangedCallback(null);
ChromecastService.setOnBookFinishedCallback(null);
+ _idleDisconnectTimer?.cancel();
+ _idleDisconnectTimer = null;
_libraries = [];
_personalizedSections = [];
_series = [];
@@ -549,6 +565,7 @@ class LibraryProvider extends ChangeNotifier {
/// Used when the device has network but the server was unreachable.
void _startServerPingTimer() {
_serverPingTimer?.cancel();
+ if (_isBackgrounded) return;
final serverUrl = _auth?.serverUrl;
if (serverUrl == null) return;
debugPrint('[Library] Starting server ping timer');
@@ -574,6 +591,65 @@ class LibraryProvider extends ChangeNotifier {
_serverPingTimer = null;
}
+ // ── Battery-saving lifecycle methods ──
+
+ /// Called when the app moves to background.
+ void onAppBackgrounded() {
+ _isBackgrounded = true;
+ _stopServerPingTimer();
+ if (!AudioPlayerService().isPlaying && !ChromecastService().isPlaying) {
+ _softDisconnectSocket();
+ }
+ }
+
+ /// Called when the app returns to foreground.
+ void onAppForegrounded() {
+ _isBackgrounded = false;
+ _softReconnectSocket();
+ // Restart ping timer if we were network-offline
+ if (_networkOffline && _deviceHasConnectivity && !_manualOffline) {
+ _startServerPingTimer();
+ }
+ _restartIdleTimer();
+ }
+
+ /// Start or restart the idle disconnect timer.
+ void _restartIdleTimer() {
+ _idleDisconnectTimer?.cancel();
+ _idleDisconnectTimer = Timer(_idleTimeout, () {
+ if (!AudioPlayerService().isPlaying && !ChromecastService().isPlaying) {
+ debugPrint('[Library] Idle timeout - soft disconnecting socket');
+ _softDisconnectSocket();
+ }
+ });
+ }
+
+ /// Called when playback starts - reconnect if needed and cancel idle timer.
+ void onPlaybackStarted() {
+ _softReconnectSocket();
+ _idleDisconnectTimer?.cancel();
+ }
+
+ /// Called when playback stops - start idle timer.
+ void onPlaybackStopped() {
+ _restartIdleTimer();
+ if (_isBackgrounded) {
+ _softDisconnectSocket();
+ }
+ }
+
+ void _softDisconnectSocket() {
+ if (_socketSoftDisconnected || _manualOffline) return;
+ _socketSoftDisconnected = true;
+ SocketService().softDisconnect();
+ }
+
+ void _softReconnectSocket() {
+ if (!_socketSoftDisconnected || _manualOffline) return;
+ _socketSoftDisconnected = false;
+ SocketService().softReconnect();
+ }
+
/// Returns true for exceptions that indicate a real network problem
/// (unreachable server, DNS failure, TLS error). Non-network errors like
/// server 500s or JSON parse failures should not trigger offline mode.
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index a6ca9bdd..ab57cebb 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -220,9 +220,12 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
+ context.read<LibraryProvider>().onAppForegrounded();
_refreshDataForTab(_currentIndex);
// Check auto sleep in case we resumed into the window
SleepTimerService().checkAutoSleep();
+ } else if (state == AppLifecycleState.paused) {
+ context.read<LibraryProvider>().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 c622eb55..23309b3f 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -21,7 +21,7 @@ import '../screens/app_shell.dart';
import '../screens/admin_screen.dart';
import '../screens/downloads_screen.dart';
import '../screens/bookmarks_screen.dart';
-import '../main.dart' show applyThemeMode, oledNotifier;
+import '../main.dart' show applyThemeMode, oledNotifier, snappyTransitionsNotifier;
import '../widgets/absorb_page_header.dart';
import '../widgets/absorb_slider.dart';
@@ -56,6 +56,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _showGoodreadsButton = false;
bool _loggingEnabled = false;
bool _fullScreenPlayer = false;
+ bool _snappyTransitions = false;
String _themeMode = 'dark';
int _streamingCacheSizeMb = 0;
bool _loaded = false;
@@ -121,12 +122,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
PlayerSettings.getLoggingEnabled(), // 21
PlayerSettings.getFullScreenPlayer(), // 22
PlayerSettings.getThemeMode(), // 23
- DownloadService().downloadLocationLabel, // 24
- DownloadService().totalDownloadSize, // 25
- DownloadService.getDeviceStorage(), // 26
- AutoSleepSettings.load(), // 27
- PackageInfo.fromPlatform(), // 28
- PlayerSettings.getStreamingCacheSizeMb(), // 29
+ PlayerSettings.getSnappyTransitions(), // 24
+ DownloadService().downloadLocationLabel, // 25
+ DownloadService().totalDownloadSize, // 26
+ DownloadService.getDeviceStorage(), // 27
+ AutoSleepSettings.load(), // 28
+ PackageInfo.fromPlatform(), // 29
+ PlayerSettings.getStreamingCacheSizeMb(), // 30
]);
final s = results[0] as AutoRewindSettings;
final speed = results[1] as double;
@@ -152,12 +154,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
final logging = results[21] as bool;
final fullScreen = results[22] as bool;
final theme = results[23] as String;
- final dlLabel = results[24] as String;
- final dlSize = results[25] as int;
- final deviceStorage = results[26] as Map<String, int>?;
- final autoSleep = results[27] as AutoSleepSettings;
- final pkgInfo = results[28] as PackageInfo;
- final cacheSizeMb = results[29] as int;
+ final snappyTrans = results[24] as bool;
+ final dlLabel = results[25] as String;
+ final dlSize = results[26] as int;
+ final deviceStorage = results[27] as Map<String, int>?;
+ final autoSleep = results[28] as AutoSleepSettings;
+ final pkgInfo = results[29] as PackageInfo;
+ final cacheSizeMb = results[30] as int;
if (mounted) setState(() {
_rewindSettings = s;
_defaultSpeed = speed;
@@ -182,6 +185,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_showGoodreadsButton = showGoodreads;
_loggingEnabled = logging;
_fullScreenPlayer = fullScreen;
+ _snappyTransitions = snappyTrans;
_themeMode = theme;
_downloadLocationLabel = dlLabel;
_totalDownloadSizeBytes = dlSize;
@@ -523,6 +527,19 @@ class _SettingsScreenState extends State<SettingsScreen> {
],
),
),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Snappy transitions'),
+ subtitle: Text(
+ _snappyTransitions ? 'On - instant page transitions' : 'Off - smooth slide animations',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _snappyTransitions,
+ onChanged: _loaded ? (v) {
+ setState(() => _snappyTransitions = v);
+ PlayerSettings.setSnappyTransitions(v);
+ snappyTransitionsNotifier.value = v;
+ } : null,
+ ),
],
),
const SizedBox(height: 16),
diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart
index f8448ed3..5cbc14f7 100644
--- a/lib/screens/stats_screen.dart
+++ b/lib/screens/stats_screen.dart
@@ -119,13 +119,13 @@ class _StatsScreenState extends State<StatsScreen>
body: Container(
decoration: oledNotifier.value ? null : BoxDecoration(
gradient: LinearGradient(
- begin: Alignment.topLeft,
- end: Alignment.bottomRight,
- stops: const [0.0, 0.4, 0.7, 1.0],
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.22, 0.72, 1.0],
colors: [
- cs.primary.withValues(alpha: 0.12),
- cs.primary.withValues(alpha: 0.04),
- Theme.of(context).scaffoldBackgroundColor,
+ cs.primary.withValues(alpha: 0.06),
+ cs.surface,
+ Color.lerp(cs.surface, Theme.of(context).scaffoldBackgroundColor, 0.55) ?? Theme.of(context).scaffoldBackgroundColor,
Theme.of(context).scaffoldBackgroundColor,
],
),
@@ -289,11 +289,11 @@ class _StatsScreenState extends State<StatsScreen>
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: oledNotifier.value ? null : LinearGradient(
- begin: Alignment.topLeft,
- end: Alignment.bottomRight,
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
colors: [
- cs.primary.withValues(alpha: 0.12),
- cs.primary.withValues(alpha: 0.04),
+ cs.primary.withValues(alpha: 0.08),
+ cs.primary.withValues(alpha: 0.02),
],
),
border: Border.all(color: cs.primary.withValues(alpha: oledNotifier.value ? 0.08 : 0.15)),
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 3ec75e4c..b2ea58e2 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -235,6 +235,9 @@ class PlayerSettings {
static Future<bool> getFullScreenPlayer() => _get('fullScreenPlayer', false);
static Future<void> setFullScreenPlayer(bool value) => _set('fullScreenPlayer', value);
+ static Future<bool> getSnappyTransitions() => _get('snappyTransitions', false);
+ static Future<void> setSnappyTransitions(bool value) => _set('snappyTransitions', value);
+
// ── Card button order ──
static const defaultButtonOrder = ['chapters', 'speed', 'sleep', 'bookmarks', 'details', 'equalizer', 'cast', 'history', 'remove'];
@@ -868,6 +871,13 @@ class AudioPlayerService extends ChangeNotifier {
_onEpisodePlayStartedCallback = cb;
}
+ /// Called when playback state changes (playing/paused). Used by
+ /// LibraryProvider for battery-saving socket lifecycle.
+ static void Function(bool isPlaying)? _onPlaybackStateChangedCallback;
+ static void setOnPlaybackStateChangedCallback(void Function(bool isPlaying)? cb) {
+ _onPlaybackStateChangedCallback = cb;
+ }
+
static AudioPlayerHandler? _handler;
static Completer<void> _initCompleter = Completer<void>();
AudioPlayer? get _player => _handler?.player;
@@ -2165,6 +2175,7 @@ class AudioPlayerService extends ChangeNotifier {
try { (await AudioSession.instance).setActive(true); } catch (_) {}
_player?.play();
_logEvent(PlaybackEventType.play);
+ _onPlaybackStateChangedCallback?.call(true);
// Check auto sleep on every resume — catches window entry between pauses
SleepTimerService().checkAutoSleep();
notifyListeners();
@@ -2176,6 +2187,7 @@ class AudioPlayerService extends ChangeNotifier {
_lastPauseTime = DateTime.now();
await _player?.pause();
_logEvent(PlaybackEventType.pause);
+ _onPlaybackStateChangedCallback?.call(false);
notifyListeners();
final pos = position;
debugPrint('[Player] Saving on pause: ${(pos.inMilliseconds / 1000.0).toStringAsFixed(1)}s');
@@ -2316,6 +2328,7 @@ class AudioPlayerService extends ChangeNotifier {
}
await _player?.stop();
+ _onPlaybackStateChangedCallback?.call(false);
_clearState();
_chapters = [];
_handler?.updateChaptersQueue(const []);
diff --git a/lib/services/socket_service.dart b/lib/services/socket_service.dart
index 27e7c3f6..8ac09df3 100644
--- a/lib/services/socket_service.dart
+++ b/lib/services/socket_service.dart
@@ -8,6 +8,9 @@ class SocketService {
IO.Socket? _socket;
String? _token;
+ String? _serverUrl;
+
+ bool get isConnected => _socket?.connected ?? false;
/// Called when the server pushes a progress update (cross-device sync).
void Function(Map<String, dynamic> progress)? onProgressUpdated;
@@ -31,6 +34,7 @@ class SocketService {
if (_socket != null) disconnect();
_token = token;
+ _serverUrl = serverUrl;
try {
_socket = IO.io(serverUrl, IO.OptionBuilder()
@@ -122,13 +126,16 @@ class SocketService {
debugPrint('[Socket] Failed to connect: $e');
_socket = null;
_token = null;
+ _serverUrl = null;
}
}
+ /// Disconnect and tear down the socket, clearing all callbacks.
void disconnect() {
_socket?.dispose();
_socket = null;
_token = null;
+ _serverUrl = null;
onProgressUpdated = null;
onItemUpdated = null;
onItemRemoved = null;
@@ -136,4 +143,83 @@ class SocketService {
onCollectionUpdated = null;
onUserUpdated = null;
}
+
+ /// Disconnect the socket but keep callbacks and credentials so we can
+ /// cheaply reconnect later without re-wiring everything.
+ void softDisconnect() {
+ if (_socket == null) return;
+ debugPrint('[Socket] Soft disconnect (battery saving)');
+ _socket!.dispose();
+ _socket = null;
+ }
+
+ /// Reconnect after a soft disconnect, reusing saved credentials.
+ void softReconnect() {
+ if (_socket != null) return; // already connected
+ final url = _serverUrl;
+ final token = _token;
+ if (url == null || token == null) return;
+ debugPrint('[Socket] Soft reconnect');
+
+ try {
+ _socket = IO.io(url, IO.OptionBuilder()
+ .setTransports(['websocket'])
+ .enableReconnection()
+ .build());
+
+ _socket!.onConnect((_) {
+ debugPrint('[Socket] Connected, sending auth');
+ _socket!.emit('auth', _token);
+ });
+
+ _socket!.on('init', (_) {
+ debugPrint('[Socket] Authenticated - user is online');
+ });
+
+ _socket!.on('auth_failed', (_) {
+ debugPrint('[Socket] Auth failed');
+ disconnect();
+ });
+
+ _socket!.on('user_item_progress_updated', (data) {
+ if (data is Map<String, dynamic>) {
+ final patch = data['data'] as Map<String, dynamic>?;
+ if (patch != null) onProgressUpdated?.call(patch);
+ }
+ });
+
+ _socket!.on('item_added', (data) {
+ if (data is Map<String, dynamic>) onItemUpdated?.call(data);
+ });
+ _socket!.on('item_updated', (data) {
+ if (data is Map<String, dynamic>) onItemUpdated?.call(data);
+ });
+ _socket!.on('item_removed', (data) {
+ if (data is Map<String, dynamic>) onItemRemoved?.call(data);
+ });
+
+ _socket!.on('series_added', (_) => onSeriesUpdated?.call());
+ _socket!.on('series_updated', (_) => onSeriesUpdated?.call());
+ _socket!.on('series_removed', (_) => onSeriesUpdated?.call());
+
+ _socket!.on('collection_added', (_) => onCollectionUpdated?.call());
+ _socket!.on('collection_updated', (_) => onCollectionUpdated?.call());
+ _socket!.on('collection_removed', (_) => onCollectionUpdated?.call());
+
+ _socket!.on('user_updated', (data) {
+ if (data is Map<String, dynamic>) onUserUpdated?.call(data);
+ });
+
+ _socket!.onDisconnect((_) {
+ debugPrint('[Socket] Disconnected');
+ });
+
+ _socket!.onConnectError((err) {
+ debugPrint('[Socket] Connect error: $err');
+ });
+ } catch (e) {
+ debugPrint('[Socket] Failed to reconnect: $e');
+ _socket = null;
+ }
+ }
}