Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix BT disconnect resume, stuck splash screen, and ebook downloads

Nathan Poulson5a3753479a30
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 ea6b69c5..03c00ab5 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -1,9 +1,13 @@
package com.barnabas.absorb
+import android.content.Context
+import android.media.AudioDeviceInfo
+import android.media.AudioManager
import android.media.audiofx.BassBoost
import android.media.audiofx.Equalizer
import android.media.audiofx.LoudnessEnhancer
import android.media.audiofx.Virtualizer
+import android.os.Build
import android.util.Log
import com.ryanheise.audioservice.AudioServiceActivity
import io.flutter.embedding.engine.FlutterEngine
@@ -29,6 +33,9 @@ class MainActivity : AudioServiceActivity() {
moveTaskToBack(true)
result.success(true)
}
+ "isBluetoothAudioConnected" -> {
+ result.success(isBluetoothAudioConnected())
+ }
"init" -> handleInit(result)
"attachSession" -> {
val sessionId = call.argument<Int>("sessionId") ?: 0
@@ -185,6 +192,19 @@ class MainActivity : AudioServiceActivity() {
loudnessEnhancer = null
}
+ private fun isBluetoothAudioConnected(): Boolean {
+ val am = getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ val devices = am.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
+ return devices.any {
+ it.type == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP ||
+ it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO
+ }
+ }
+ @Suppress("DEPRECATION")
+ return am.isBluetoothA2dpOn || am.isBluetoothScoOn
+ }
+
override fun onDestroy() {
releaseEffects()
super.onDestroy()
diff --git a/lib/main.dart b/lib/main.dart
index 3ee38d9f..8f8d8ef5 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -48,7 +48,15 @@ void main() async {
// stares at a loading spinner. Downloads must be loaded before the
// handler so getChildren() can serve the browse tree immediately.
await DownloadService().init();
- await AudioPlayerService.init();
+ // Timeout guards against AudioService.init() hanging when Android killed
+ // the app process but kept the MediaBrowserService alive (e.g. Bluetooth
+ // or Android Auto was connected). If it times out the app still launches
+ // and _initServices() in AuthGate will retry.
+ try {
+ await AudioPlayerService.init().timeout(const Duration(seconds: 8));
+ } catch (e) {
+ debugPrint('[Main] AudioPlayerService.init timed out or failed: $e');
+ }
// Lock to portrait — no landscape support
await SystemChrome.setPreferredOrientations([
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 46ac53a8..66739507 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -452,6 +452,8 @@ class LibraryProvider extends ChangeNotifier {
loadLibraries();
}).catchError((e) {
debugPrint('[Library] restoreOfflineMode error: $e');
+ _isLoading = false;
+ notifyListeners();
});
} else {
_lastAuthKey = null;
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 7400d4c6..2c5f014e 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:just_audio/just_audio.dart';
import 'package:audio_service/audio_service.dart';
import 'package:audio_session/audio_session.dart';
@@ -1032,6 +1033,21 @@ class AudioPlayerService extends ChangeNotifier {
// Set true when BT/headphones disconnect so the interruption handler
// won't auto-resume playback onto the phone speaker.
static bool _noisyPause = false;
+ // Whether BT audio was connected when the current interruption began.
+ static bool _wasOnBluetooth = false;
+ static const _eqChannel = MethodChannel('com.absorb.equalizer');
+
+ /// Check if BT audio (A2DP/SCO) is currently connected via native AudioManager.
+ static Future<bool> _isBluetoothAudioConnected() async {
+ try {
+ final result = await _eqChannel.invokeMethod<bool>('isBluetoothAudioConnected');
+ return result ?? false;
+ } catch (e) {
+ debugPrint('[AudioSession] BT check failed: $e');
+ return false;
+ }
+ }
+
/// True when BT/headphones just disconnected — callers can check before
/// starting new playback to avoid blasting audio on the phone speaker.
static bool get wasNoisyPause => _noisyPause;
@@ -1048,6 +1064,8 @@ class AudioPlayerService extends ChangeNotifier {
if (event.begin) {
if (service.isPlaying) {
debugPrint('[AudioSession] Interrupted (${event.type}) — pausing');
+ _wasOnBluetooth = await _isBluetoothAudioConnected();
+ debugPrint('[AudioSession] Was on BT: $_wasOnBluetooth');
// Pause the underlying player directly — NOT service.pause() —
// to keep the interruption lightweight. service.pause() saves progress,
// syncs to server, clears _wasPlayingBeforeInterrupt, and sets
@@ -1066,12 +1084,24 @@ class AudioPlayerService extends ChangeNotifier {
return;
}
if (service._wasPlayingBeforeInterrupt) {
- debugPrint('[AudioSession] Interruption ended — resuming');
service._wasPlayingBeforeInterrupt = false;
- await Future.delayed(const Duration(milliseconds: 300));
+ await Future.delayed(const Duration(milliseconds: 600));
// Re-check: another event (like becoming-noisy) might have fired
// during the delay.
if (_noisyPause) return;
+ // If we were on BT when interrupted, check if BT is still connected.
+ // Some car head units never send AUDIO_BECOMING_NOISY on disconnect,
+ // so _noisyPause alone is not enough.
+ if (_wasOnBluetooth) {
+ final stillOnBt = await _isBluetoothAudioConnected();
+ debugPrint('[AudioSession] Interruption ended — was BT, still BT: $stillOnBt');
+ if (!stillOnBt) {
+ debugPrint('[AudioSession] BT disconnected during interruption — skipping resume');
+ _noisyPause = true;
+ return;
+ }
+ }
+ debugPrint('[AudioSession] Interruption ended — resuming');
await service.play();
}
}
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index b30d7715..97d1c662 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -553,13 +553,29 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
final cleanBase = api.baseUrl.endsWith('/') ? api.baseUrl.substring(0, api.baseUrl.length - 1) : api.baseUrl;
final url = '$cleanBase/api/items/${widget.itemId}/file/$ino';
- // Use streamed download to avoid loading entire file into memory
- // and to prevent timeout-based truncation of large files
+ // Use streamed download with proper headers (including custom
+ // reverse-proxy headers) and manual redirect following so auth
+ // headers are preserved across redirects.
final request = http.Request('GET', Uri.parse(url));
- request.headers['Authorization'] = 'Bearer ${api.token}';
+ request.followRedirects = false;
+ api.mediaHeaders.forEach((k, v) => request.headers[k] = v);
final client = http.Client();
try {
- final response = await client.send(request);
+ var response = await client.send(request);
+
+ // Manually follow redirects while preserving auth headers
+ var redirects = 0;
+ while ([301, 302, 303, 307, 308].contains(response.statusCode) && redirects < 5) {
+ final location = response.headers['location'];
+ if (location == null) break;
+ final redirectUrl = Uri.parse(url).resolve(location);
+ final rReq = http.Request('GET', redirectUrl);
+ api.mediaHeaders.forEach((k, v) => rReq.headers[k] = v);
+ rReq.followRedirects = false;
+ response = await client.send(rReq);
+ redirects++;
+ }
+
if (response.statusCode != 200) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
@@ -567,6 +583,19 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
}
return;
}
+
+ // Sanity-check: if the server returned HTML instead of a binary
+ // file, the download is likely an error/login page.
+ final ct = response.headers['content-type'] ?? '';
+ if (ct.contains('text/html')) {
+ debugPrint('[Ebook] Server returned HTML instead of ebook file (content-type: $ct)');
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(content: Text('Server returned an error page instead of the ebook file')));
+ }
+ return;
+ }
+
final sink = cachedFile.openWrite();
try {
await response.stream.pipe(sink);