Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Improve shake detection, add 3-way shake mode, persist sleep timer settings

Nathan Poulsone5cfda2ceceb
diff --git a/lib/main.dart b/lib/main.dart
index 883e8c00..78524538 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -298,6 +298,11 @@ class _AuthGateState extends State<AuthGate> {
final sw = Stopwatch()..start();
debugPrint('[Init] _initServices started');
+ // Initialize user account scope FIRST so all ScopedPrefs reads use the
+ // correct scoped keys. Without this, settings read before init() would
+ // fall back to un-scoped keys and appear as defaults.
+ await UserAccountService().init();
+
// Start auth restoration immediately — it doesn't depend on audio/cast/
// download services and must not be blocked by a hanging service init.
if (mounted) {
@@ -367,7 +372,6 @@ class _AuthGateState extends State<AuthGate> {
// Initialize download tracker and progress sync
debugPrint('[Init] remaining services... (${sw.elapsedMilliseconds}ms)');
try {
- await UserAccountService().init();
await ProgressSyncService().init();
await EqualizerService().init();
await SleepTimerService().loadAutoSleepSettings();
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index e151fc66..5b6d4671 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -42,7 +42,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _speedAdjustedTime = true;
int _forwardSkip = 30;
int _backSkip = 10;
- bool _shakeToResetSleep = true;
+ String _shakeMode = 'addTime';
bool _resetSleepOnPause = false;
bool _sleepFadeOut = true;
int _shakeAddMinutes = 5;
@@ -105,7 +105,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
PlayerSettings.getSpeedAdjustedTime(), // 7
PlayerSettings.getForwardSkip(), // 8
PlayerSettings.getBackSkip(), // 9
- PlayerSettings.getShakeToResetSleep(), // 10
+ PlayerSettings.getShakeMode(), // 10
PlayerSettings.getResetSleepOnPause(), // 11
PlayerSettings.getSleepFadeOut(), // 12
PlayerSettings.getShakeAddMinutes(), // 13
@@ -135,7 +135,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
final speedAdj = results[7] as bool;
final fwd = results[8] as int;
final bk = results[9] as int;
- final shake = results[10] as bool;
+ final shake = results[10] as String;
final resetOnPause = results[11] as bool;
final sleepFade = results[12] as bool;
final shakeMins = results[13] as int;
@@ -165,7 +165,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_speedAdjustedTime = speedAdj;
_forwardSkip = fwd;
_backSkip = bk;
- _shakeToResetSleep = shake;
+ _shakeMode = shake;
_resetSleepOnPause = resetOnPause;
_sleepFadeOut = sleepFade;
_shakeAddMinutes = shakeMins;
@@ -910,18 +910,29 @@ class _SettingsScreenState extends State<SettingsScreen> {
isExpanded: _expandedSection == 'Sleep Timer',
onExpansionChanged: (v) => _onSectionExpanded('Sleep Timer', v),
children: [
- SwitchListTile(
- title: const Text('Shake to add time'),
- subtitle: Text(
- _shakeToResetSleep ? 'On — adds $_shakeAddMinutes min per shake' : 'Off',
- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
- value: _shakeToResetSleep,
- onChanged: _loaded ? (v) {
- setState(() => _shakeToResetSleep = v);
- PlayerSettings.setShakeToResetSleep(v);
- } : null,
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
+ child: Text('Shake during sleep timer', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
+ child: SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<String>(
+ segments: const [
+ ButtonSegment(value: 'off', label: Text('Off')),
+ ButtonSegment(value: 'addTime', label: Text('Add Time')),
+ ButtonSegment(value: 'resetTimer', label: Text('Reset')),
+ ],
+ selected: {_shakeMode},
+ onSelectionChanged: _loaded ? (v) {
+ setState(() => _shakeMode = v.first);
+ PlayerSettings.setShakeMode(v.first);
+ } : null,
+ ),
+ ),
),
- if (_shakeToResetSleep) ...[
+ if (_shakeMode == 'addTime') ...[
const Divider(height: 1, indent: 16, endIndent: 16),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 0458c36f..85590589 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -152,12 +152,19 @@ class PlayerSettings {
// ── Sleep timer settings ──
- static Future<bool> getShakeToResetSleep() => _get('shakeToResetSleep', true);
- static Future<void> setShakeToResetSleep(bool value) => _set('shakeToResetSleep', value);
+ // 'off', 'addTime', 'resetTimer'
+ static Future<String> getShakeMode() => _get('shakeMode', 'addTime');
+ static Future<void> setShakeMode(String value) => _set('shakeMode', value);
static Future<int> getShakeAddMinutes() => _get('shakeAddMinutes', 5);
static Future<void> setShakeAddMinutes(int minutes) => _set('shakeAddMinutes', minutes);
+ static Future<int> getSleepTimerMinutes() => _get('sleepTimerMinutes', 30);
+ static Future<void> setSleepTimerMinutes(int minutes) => _set('sleepTimerMinutes', minutes);
+
+ static Future<int> getSleepTimerChapters() => _get('sleepTimerChapters', 1);
+ static Future<void> setSleepTimerChapters(int chapters) => _set('sleepTimerChapters', chapters);
+
static Future<bool> getResetSleepOnPause() => _get('resetSleepOnPause', false);
static Future<void> setResetSleepOnPause(bool value) => _set('resetSleepOnPause', value);
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 33683663..3f98f628 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -26,7 +26,7 @@ class BackupService {
'speedAdjustedTime': await PlayerSettings.getSpeedAdjustedTime(),
'forwardSkip': await PlayerSettings.getForwardSkip(),
'backSkip': await PlayerSettings.getBackSkip(),
- 'shakeToResetSleep': await PlayerSettings.getShakeToResetSleep(),
+ 'shakeMode': await PlayerSettings.getShakeMode(),
'shakeAddMinutes': await PlayerSettings.getShakeAddMinutes(),
'resetSleepOnPause': await PlayerSettings.getResetSleepOnPause(),
'sleepFadeOut': await PlayerSettings.getSleepFadeOut(),
@@ -164,7 +164,11 @@ class BackupService {
if (s['speedAdjustedTime'] != null) PlayerSettings.setSpeedAdjustedTime(s['speedAdjustedTime'] as bool);
if (s['forwardSkip'] != null) PlayerSettings.setForwardSkip(s['forwardSkip'] as int);
if (s['backSkip'] != null) PlayerSettings.setBackSkip(s['backSkip'] as int);
- if (s['shakeToResetSleep'] != null) PlayerSettings.setShakeToResetSleep(s['shakeToResetSleep'] as bool);
+ if (s['shakeMode'] != null) PlayerSettings.setShakeMode(s['shakeMode'] as String);
+ // Migrate old bool setting
+ if (s['shakeMode'] == null && s['shakeToResetSleep'] != null) {
+ PlayerSettings.setShakeMode(s['shakeToResetSleep'] as bool ? 'addTime' : 'off');
+ }
if (s['shakeAddMinutes'] != null) PlayerSettings.setShakeAddMinutes(s['shakeAddMinutes'] as int);
if (s['resetSleepOnPause'] != null) PlayerSettings.setResetSleepOnPause(s['resetSleepOnPause'] as bool);
if (s['sleepFadeOut'] != null) PlayerSettings.setSleepFadeOut(s['sleepFadeOut'] as bool);
diff --git a/lib/services/sleep_timer_service.dart b/lib/services/sleep_timer_service.dart
index 21523738..be21622e 100644
--- a/lib/services/sleep_timer_service.dart
+++ b/lib/services/sleep_timer_service.dart
@@ -1,8 +1,8 @@
import 'dart:async';
import 'dart:math';
import 'package:flutter/foundation.dart';
-import 'package:flutter/services.dart';
import 'package:sensors_plus/sensors_plus.dart';
+import 'package:vibration/vibration.dart';
import 'scoped_prefs.dart';
import 'audio_player_service.dart';
import 'chromecast_service.dart';
@@ -98,10 +98,10 @@ class SleepTimerService extends ChangeNotifier {
StreamSubscription? _positionSub;
// Shake detection
- bool _shakeEnabled = true;
+ String _shakeMode = 'addTime'; // 'off', 'addTime', 'resetTimer'
StreamSubscription? _accelSub;
DateTime _lastShake = DateTime(2000);
- static const _shakeThreshold = 25.0; // m/s² — raised from 15 to require a deliberate shake
+ static const _shakeThreshold = 20.0; // m/s² of linear acceleration (gravity excluded)
static const _shakeCooldown = Duration(seconds: 3);
// Wind-down warning & fade
@@ -121,7 +121,7 @@ class SleepTimerService extends ChangeNotifier {
: 0.0;
int get chaptersRemaining => _chaptersRemaining;
bool get isActive => _mode != SleepTimerMode.off;
- bool get shakeEnabled => _shakeEnabled;
+ String get shakeMode => _shakeMode;
String get displayLabel {
if (_mode == SleepTimerMode.time) {
@@ -335,23 +335,24 @@ class SleepTimerService extends ChangeNotifier {
// ── Haptic feedback ──
- /// Medium buzz when shake-snooze adds time
- void _vibrateSnooze() {
- HapticFeedback.mediumImpact();
+ /// Double buzz when shake-snooze adds time
+ void _vibrateSnooze() async {
+ if (await Vibration.hasVibrator()) {
+ Vibration.vibrate(pattern: [0, 150, 100, 150]);
+ }
}
// ── Shake detection ──
Future<void> _startShakeDetection() async {
- _shakeEnabled = await PlayerSettings.getShakeToResetSleep();
- if (!_shakeEnabled) return;
+ _shakeMode = await PlayerSettings.getShakeMode();
+ if (_shakeMode == 'off') return;
_accelSub?.cancel();
- _accelSub = accelerometerEventStream().listen((event) {
+ _accelSub = userAccelerometerEventStream().listen((event) {
final magnitude = sqrt(
event.x * event.x + event.y * event.y + event.z * event.z);
- // Subtract gravity (~9.8) and check threshold
if (magnitude > _shakeThreshold) {
final now = DateTime.now();
if (now.difference(_lastShake) > _shakeCooldown) {
@@ -359,6 +360,8 @@ class SleepTimerService extends ChangeNotifier {
_onShake();
}
}
+ }, onError: (e) {
+ debugPrint('[SleepTimer] Accelerometer error: $e');
});
}
@@ -465,17 +468,31 @@ class SleepTimerService extends ChangeNotifier {
void _onShake() async {
if (!isActive) return;
- debugPrint('[SleepTimer] Shake detected!');
-
+ _shakeMode = await PlayerSettings.getShakeMode();
+ if (_shakeMode == 'off') return;
+ debugPrint('[SleepTimer] Shake detected! mode=$_shakeMode');
+
_vibrateSnooze();
- if (_mode == SleepTimerMode.time) {
- final addMins = await PlayerSettings.getShakeAddMinutes();
- addTime(Duration(minutes: addMins));
- onToast?.call('+$addMins min added!');
- } else if (_mode == SleepTimerMode.chapters) {
- addChapter();
- onToast?.call('+1 chapter added!');
+ if (_shakeMode == 'resetTimer') {
+ if (_mode == SleepTimerMode.time) {
+ _timeRemaining = _initialDuration;
+ _warningSent = false;
+ notifyListeners();
+ onToast?.call('Timer reset to ${_initialDuration.inMinutes}m');
+ } else if (_mode == SleepTimerMode.chapters) {
+ // For chapter mode, re-count from current position
+ onToast?.call('Timer reset');
+ }
+ } else if (_shakeMode == 'addTime') {
+ if (_mode == SleepTimerMode.time) {
+ final addMins = await PlayerSettings.getShakeAddMinutes();
+ addTime(Duration(minutes: addMins));
+ onToast?.call('+$addMins min added!');
+ } else if (_mode == SleepTimerMode.chapters) {
+ addChapter();
+ onToast?.call('+1 chapter added!');
+ }
}
}
diff --git a/lib/widgets/sleep_timer_sheet.dart b/lib/widgets/sleep_timer_sheet.dart
index c4b98c2a..9b92cca9 100644
--- a/lib/widgets/sleep_timer_sheet.dart
+++ b/lib/widgets/sleep_timer_sheet.dart
@@ -22,7 +22,7 @@ class _SleepTimerSheetState extends State<SleepTimerSheet> {
int _tabIndex = 0; // 0 = Timer, 1 = End of Chapter
double _customMinutes = 30;
int _customChapters = 1;
- bool _shakeEnabled = true;
+ String _shakeMode = 'addTime'; // 'off', 'addTime', 'resetTimer'
int _shakeAddMinutes = 5;
@override
@@ -32,9 +32,16 @@ class _SleepTimerSheetState extends State<SleepTimerSheet> {
}
Future<void> _loadShakeSettings() async {
- final shake = await PlayerSettings.getShakeToResetSleep();
+ final mode = await PlayerSettings.getShakeMode();
final mins = await PlayerSettings.getShakeAddMinutes();
- if (mounted) setState(() { _shakeEnabled = shake; _shakeAddMinutes = mins; });
+ final timerMins = await PlayerSettings.getSleepTimerMinutes();
+ final timerCh = await PlayerSettings.getSleepTimerChapters();
+ if (mounted) setState(() {
+ _shakeMode = mode;
+ _shakeAddMinutes = mins;
+ _customMinutes = timerMins.toDouble();
+ _customChapters = timerCh;
+ });
}
@override
@@ -250,6 +257,7 @@ class _SleepTimerSheetState extends State<SleepTimerSheet> {
style: FilledButton.styleFrom(backgroundColor: accent, foregroundColor: cs.surface,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
onPressed: () {
+ PlayerSettings.setSleepTimerMinutes(_customMinutes.round());
SleepTimerService().setTimeSleep(Duration(minutes: _customMinutes.round()));
Navigator.pop(context);
},
@@ -289,6 +297,7 @@ class _SleepTimerSheetState extends State<SleepTimerSheet> {
style: FilledButton.styleFrom(backgroundColor: accent, foregroundColor: cs.surface,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
onPressed: () {
+ PlayerSettings.setSleepTimerChapters(_customChapters);
SleepTimerService().setChapterSleep(_customChapters);
Navigator.pop(context);
},
@@ -300,28 +309,79 @@ class _SleepTimerSheetState extends State<SleepTimerSheet> {
Widget _buildShakeToggle(Color accent, TextTheme tt) {
final cs = Theme.of(context).colorScheme;
- return Row(children: [
- Icon(Icons.vibration_rounded, size: 18, color: _shakeEnabled ? accent : cs.onSurface.withValues(alpha: 0.24)),
- const SizedBox(width: 10),
- Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
- Text('Shake to add time',
- style: TextStyle(color: _shakeEnabled ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 13, fontWeight: FontWeight.w500)),
- Text(_shakeEnabled
- ? (_tabIndex == 0 ? 'Adds $_shakeAddMinutes min' : 'Adds 1 chapter')
- : 'Off',
- style: TextStyle(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 11)),
- ])),
+ final isEnabled = _shakeMode != 'off';
+ String subtitle;
+ if (_shakeMode == 'addTime') {
+ subtitle = _tabIndex == 0 ? 'Adds $_shakeAddMinutes min' : 'Adds 1 chapter';
+ } else if (_shakeMode == 'resetTimer') {
+ subtitle = 'Resets to full duration';
+ } else {
+ subtitle = 'Disabled';
+ }
+ return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(children: [
+ Icon(Icons.vibration_rounded, size: 18, color: isEnabled ? accent : cs.onSurface.withValues(alpha: 0.24)),
+ const SizedBox(width: 10),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text('Shake', style: TextStyle(color: isEnabled ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 13, fontWeight: FontWeight.w500)),
+ Text(subtitle, style: TextStyle(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 11)),
+ ])),
+ ]),
+ const SizedBox(height: 10),
SizedBox(
- height: 28,
- child: Switch(
- value: _shakeEnabled,
- activeTrackColor: accent,
- onChanged: (v) {
- setState(() => _shakeEnabled = v);
- PlayerSettings.setShakeToResetSleep(v);
+ width: double.infinity,
+ child: SegmentedButton<String>(
+ segments: const [
+ ButtonSegment(value: 'off', label: Text('Off')),
+ ButtonSegment(value: 'addTime', label: Text('Add Time')),
+ ButtonSegment(value: 'resetTimer', label: Text('Reset')),
+ ],
+ selected: {_shakeMode},
+ style: ButtonStyle(
+ visualDensity: VisualDensity.compact,
+ textStyle: WidgetStatePropertyAll(TextStyle(fontSize: 12)),
+ ),
+ onSelectionChanged: (v) {
+ setState(() => _shakeMode = v.first);
+ PlayerSettings.setShakeMode(v.first);
},
),
),
+ AnimatedOpacity(
+ opacity: _shakeMode == 'addTime' ? 1.0 : 0.0,
+ duration: const Duration(milliseconds: 200),
+ child: IgnorePointer(
+ ignoring: _shakeMode != 'addTime',
+ child: Column(children: [
+ const SizedBox(height: 8),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('Shake adds', style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12)),
+ Text('$_shakeAddMinutes min',
+ style: TextStyle(fontWeight: FontWeight.w600, color: accent, fontSize: 12)),
+ ],
+ ),
+ SliderTheme(
+ data: SliderThemeData(
+ activeTrackColor: accent,
+ inactiveTrackColor: cs.onSurface.withValues(alpha: 0.1),
+ thumbColor: accent,
+ overlayColor: accent.withValues(alpha: 0.1),
+ trackHeight: 4,
+ ),
+ child: Slider(
+ value: _shakeAddMinutes.toDouble(),
+ min: 1, max: 30, divisions: 29,
+ onChanged: (v) {
+ setState(() => _shakeAddMinutes = v.round());
+ PlayerSettings.setShakeAddMinutes(v.round());
+ },
+ ),
+ ),
+ ]),
+ ),
+ ),
]);
}
diff --git a/pubspec.lock b/pubspec.lock
index 37699885..432ece08 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -1060,6 +1060,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.2.0"
+ vibration:
+ dependency: "direct main"
+ description:
+ name: vibration
+ sha256: "9bb06614c69260f8bd11c80fe01ed7988905cf00e3417d656c2647e41f261d87"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.8"
+ vibration_platform_interface:
+ dependency: transitive
+ description:
+ name: vibration_platform_interface
+ sha256: "4134fbfcd427b59a7a91f8733292e4e9b29a7f1e8224ff0d80f5745fbf0743c6"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.1.1"
vm_service:
dependency: transitive
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index f4ed9551..66e151db 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: A Material 3 Audiobookshelf client.
publish_to: 'none'
-version: 1.8.7+38
+version: 1.8.8+39
environment:
sdk: '>=3.1.0 <4.0.0'
@@ -74,6 +74,7 @@ dependencies:
# Splash screen (preserve during init)
flutter_native_splash: ^2.4.4
+ vibration: ^3.1.8
dev_dependencies:
flutter_test: