Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

fix: cast foreground service to prevent Doze throttling listen stats (#184)

Barnabasd34bd764a63f
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 75316599..eddd8638 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -92,6 +92,14 @@
android:exported="false"
android:foregroundServiceType="dataSync" />
+ <!-- Keeps the Absorb process alive (out of Doze) during Chromecast
+ playback so the Dart-side listening-time sync timer isn't
+ throttled. Fixes GH #184. -->
+ <service
+ android:name=".CastForegroundService"
+ android:exported="false"
+ android:foregroundServiceType="mediaPlayback" />
+
<!-- FileProvider for share_plus file sharing -->
<provider
android:name="androidx.core.content.FileProvider"
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/CastForegroundService.kt b/android/app/src/main/kotlin/com/barnabas/absorb/CastForegroundService.kt
new file mode 100644
index 00000000..44bf2a7a
--- /dev/null
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/CastForegroundService.kt
@@ -0,0 +1,107 @@
+package com.barnabas.absorb
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.os.IBinder
+import android.util.Log
+import androidx.core.app.NotificationCompat
+
+/**
+ * Lightweight foreground service that keeps the Absorb process alive during
+ * Chromecast playback. The Cast SDK's notification is owned by Google Play
+ * Services, so it does not promote Absorb's process to foreground. Without
+ * this service, Android Doze throttles the Dart-side listening-time sync
+ * timer when the screen is locked, causing cast listening stats to be
+ * severely undercounted (GH #184).
+ *
+ * Notification is set to IMPORTANCE_MIN / PRIORITY_MIN so it stays collapsed
+ * in the shade and does not duplicate the Cast SDK's transport notification.
+ */
+class CastForegroundService : Service() {
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ Log.d(TAG, "onStartCommand - promoting to foreground")
+ ensureChannel()
+ val notification = buildNotification()
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ startForeground(
+ NOTIFICATION_ID,
+ notification,
+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
+ )
+ } else {
+ startForeground(NOTIFICATION_ID, notification)
+ }
+ return START_NOT_STICKY
+ }
+
+ override fun onDestroy() {
+ Log.d(TAG, "onDestroy - releasing foreground")
+ super.onDestroy()
+ }
+
+ private fun ensureChannel() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
+ val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ if (nm.getNotificationChannel(CHANNEL_ID) != null) return
+ val channel = NotificationChannel(
+ CHANNEL_ID,
+ "Chromecast session",
+ NotificationManager.IMPORTANCE_MIN
+ ).apply {
+ description = "Keeps Absorb running while casting so listening stats sync."
+ setShowBadge(false)
+ }
+ nm.createNotificationChannel(channel)
+ }
+
+ private fun buildNotification(): Notification {
+ val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
+ val pendingIntent = launchIntent?.let {
+ val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ } else {
+ PendingIntent.FLAG_UPDATE_CURRENT
+ }
+ PendingIntent.getActivity(this, 0, it, flags)
+ }
+ return NotificationCompat.Builder(this, CHANNEL_ID)
+ .setContentTitle("Absorb")
+ .setContentText("Casting")
+ .setSmallIcon(R.drawable.ic_notification)
+ .setPriority(NotificationCompat.PRIORITY_MIN)
+ .setCategory(NotificationCompat.CATEGORY_SERVICE)
+ .setSilent(true)
+ .setOngoing(true)
+ .setShowWhen(false)
+ .setContentIntent(pendingIntent)
+ .build()
+ }
+
+ companion object {
+ private const val TAG = "CastForegroundService"
+ private const val CHANNEL_ID = "absorb_cast_session"
+ private const val NOTIFICATION_ID = 9003
+
+ fun start(context: Context) {
+ val intent = Intent(context, CastForegroundService::class.java)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.startForegroundService(intent)
+ } else {
+ context.startService(intent)
+ }
+ }
+
+ fun stop(context: Context) {
+ context.stopService(Intent(context, CastForegroundService::class.java))
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
index d18b2677..81f09295 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -98,6 +98,21 @@ class MainActivity : AudioServiceActivity() {
else -> result.notImplemented()
}
}
+
+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.absorb.cast_service")
+ .setMethodCallHandler { call, result ->
+ when (call.method) {
+ "start" -> {
+ CastForegroundService.start(this)
+ result.success(true)
+ }
+ "stop" -> {
+ CastForegroundService.stop(this)
+ result.success(true)
+ }
+ else -> result.notImplemented()
+ }
+ }
}
private fun handleInit(result: MethodChannel.Result) {
diff --git a/lib/services/chromecast_service.dart b/lib/services/chromecast_service.dart
index 14d6827d..797f093d 100644
--- a/lib/services/chromecast_service.dart
+++ b/lib/services/chromecast_service.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_chrome_cast/flutter_chrome_cast.dart';
import 'api_service.dart';
@@ -69,6 +70,26 @@ class ChromecastService extends ChangeNotifier {
final _progressSync = ProgressSyncService();
bool _initialized = false;
bool _isCompletingBook = false;
+ bool _foregroundServiceActive = false;
+
+ /// Method channel to the native Android CastForegroundService. The Cast SDK
+ /// notification lives in Google Play Services' process, so Absorb's process
+ /// has no foreground promotion during cast by default - Android Doze then
+ /// throttles the 15s sync timer to ~9-15 min intervals under screen-lock.
+ /// Fixes GH #184.
+ static const MethodChannel _castServiceChannel =
+ MethodChannel('com.absorb.cast_service');
+
+ Future<void> _setForegroundService(bool active) async {
+ if (!Platform.isAndroid) return;
+ if (active == _foregroundServiceActive) return;
+ _foregroundServiceActive = active;
+ try {
+ await _castServiceChannel.invokeMethod(active ? 'start' : 'stop');
+ } catch (e) {
+ debugPrint('[Cast] setForegroundService($active) error: $e');
+ }
+ }
// Grace periods for transient cast hiccups. Idle/disconnect events during
// active casting can be spurious (network blips, track transitions, stream
@@ -167,6 +188,7 @@ class ChromecastService extends ChangeNotifier {
void _onDisconnected() {
if (_castingItemId != null && _castPosition > Duration.zero) _saveProgressLocal();
+ unawaited(_setForegroundService(false));
_connectionState = CastConnectionState.disconnected;
_playbackState = CastPlaybackState.idle;
_connectedDeviceName = null;
@@ -346,7 +368,18 @@ class ChromecastService extends ChangeNotifier {
_syncTimer = Timer.periodic(const Duration(seconds: 15), (_) {
if (isCasting && _castingItemId != null) {
_saveProgressLocal();
- _syncProgressToServer();
+ // Only report listening time while actually playing. Wall-clock
+ // elapsed would otherwise inflate server stats during pauses.
+ // Explicit pause/play/stop paths still call _syncProgressToServer
+ // directly to flush pending listening time around state changes.
+ if (isPlaying) {
+ _syncProgressToServer();
+ } else {
+ // Advance the sync baseline so a direct sync later (disconnect,
+ // stop, remote resume) doesn't bill the paused seconds as
+ // timeListened.
+ _lastSyncTime = DateTime.now();
+ }
}
});
}
@@ -384,6 +417,7 @@ class ChromecastService extends ChangeNotifier {
try { await _api!.closePlaybackSession(_playbackSessionId!); } catch (_) {}
_playbackSessionId = null;
}
+ await _setForegroundService(false);
try {
await GoogleCastSessionManager.instance.endSessionAndStopCasting();
} catch (e) { debugPrint('[Cast] Disconnect error: $e'); }
@@ -463,6 +497,9 @@ class ChromecastService extends ChangeNotifier {
_playbackSessionId = sessionData['id'] as String?;
_lastSyncTime = DateTime.now();
+ // Promote Absorb's process to foreground so Doze doesn't throttle the
+ // per-15s sync timer when the user locks their screen. See GH #184.
+ unawaited(_setForegroundService(true));
// Load per-book speed (or global default)
final bookSpeed = await PlayerSettings.getBookSpeed(itemId);
@@ -489,9 +526,14 @@ class ChromecastService extends ChangeNotifier {
debugPrint('[Cast] setPlaybackRate error: $e');
}
}
+ if (!loaded) {
+ // loadMedia failed - release the foreground promotion we took above.
+ await _setForegroundService(false);
+ }
return loaded;
} catch (e, st) {
debugPrint('[Cast] castItem error: $e\n$st');
+ await _setForegroundService(false);
_playbackState = CastPlaybackState.idle; notifyListeners(); return false;
}
}
@@ -715,7 +757,14 @@ class ChromecastService extends ChangeNotifier {
// ── Controls ──
- Future<void> play() async { if (isConnected) try { await GoogleCastRemoteMediaClient.instance.play(); } catch (_) {} }
+ Future<void> play() async {
+ if (!isConnected) return;
+ try { await GoogleCastRemoteMediaClient.instance.play(); } catch (_) {}
+ // Reset the sync clock so the first tick after resume only counts the
+ // seconds actually played since now, not the wall-clock elapsed since
+ // the last sync (which would include the entire pause).
+ _lastSyncTime = DateTime.now();
+ }
Future<void> pause() async {
if (!isConnected) return;
try { await GoogleCastRemoteMediaClient.instance.pause(); } catch (_) {}
@@ -770,6 +819,7 @@ class ChromecastService extends ChangeNotifier {
_playbackSessionId = null;
}
+ await _setForegroundService(false);
_playbackState = CastPlaybackState.idle;
_castingItemId = _castingEpisodeId = _castingTitle = _castingAuthor = _castingCoverUrl = null;
_castingDuration = 0; _castingChapters = [];
@@ -836,6 +886,7 @@ class ChromecastService extends ChangeNotifier {
// Clear casting state but keep connection
_syncTimer?.cancel();
+ await _setForegroundService(false);
_castingItemId = _castingEpisodeId = _castingTitle = _castingAuthor = _castingCoverUrl = null;
_castingDuration = 0;
_castingChapters = [];
@@ -862,6 +913,7 @@ class ChromecastService extends ChangeNotifier {
_lastSyncTime = now;
if (_playbackSessionId != null) {
+ debugPrint('[CastSync] ct=${ct.toStringAsFixed(1)}s timeListened=${elapsed}s sid=${_playbackSessionId!.substring(0, 8)}...');
// Sync via playback session so timeListened is tracked in stats
await _api!.syncPlaybackSession(
_playbackSessionId!,