A cross platform Audiobookshelf client for Android and iOS
Dart
Fix splash screen freeze when Android Auto cold-starts the app
Nathan Poulson6cf8b9a2916b
diff --git a/lib/main.dart b/lib/main.dartindex 9e6573a8..b9a9647a 100644--- a/lib/main.dart+++ b/lib/main.dart@@ -43,20 +43,27 @@ ThemeMode parseThemeMode(String value) {void main() async {final widgetsBinding = WidgetsFlutterBinding.ensureInitialized();- FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);- // Only do the bare minimum before runApp() so the UI appears fast.- // Everything else moves to AuthGate._initServices().-- // Lock to portrait — no landscape support- await SystemChrome.setPreferredOrientations([- DeviceOrientation.portraitUp,- DeviceOrientation.portraitDown,- ]);+ // These calls use platform channels that require an Activity. When Android+ // Auto cold-starts the app for the MediaBrowserService, no Activity exists+ // and these calls can hang forever - blocking runApp() and freezing on the+ // splash screen. Wrap in try-catch with a timeout so we always reach runApp().+ try {+ FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);+ } catch (_) {}++ try {+ await SystemChrome.setPreferredOrientations([+ DeviceOrientation.portraitUp,+ DeviceOrientation.portraitDown,+ ]).timeout(const Duration(seconds: 2));+ } catch (_) {}// Load saved theme preference so we render the correct theme immediately- final savedTheme = await PlayerSettings.getThemeMode();- themeNotifier.value = parseThemeMode(savedTheme);+ try {+ final savedTheme = await PlayerSettings.getThemeMode();+ themeNotifier.value = parseThemeMode(savedTheme);+ } catch (_) {}// Capture Flutter framework errors (widget build failures, etc.)FlutterError.onError = (details) {@@ -71,7 +78,9 @@ void main() async {};// Remove native splash — Flutter will render the AuthGate splash immediately- FlutterNativeSplash.remove();+ try {+ FlutterNativeSplash.remove();+ } catch (_) {}runApp(MultiProvider(@@ -278,6 +287,16 @@ class _AuthGateState extends State<AuthGate> {}Future<void> _initServices() async {+ // Initialize log service FIRST so all debugPrint calls are captured in the+ // log file. This is critical for diagnosing startup freezes in production.+ try {+ final loggingEnabled = await PlayerSettings.getLoggingEnabled();+ await LogService().init(loggingEnabled);+ } catch (_) {}++ final sw = Stopwatch()..start();+ debugPrint('[Init] _initServices started');+// 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) {@@ -285,9 +304,11 @@ class _AuthGateState extends State<AuthGate> {}// Migrate old auto-play booleans → unified queueMode (one-time, no-op after first run)+ debugPrint('[Init] migrateQueueMode... (${sw.elapsedMilliseconds}ms)');await PlayerSettings.migrateQueueMode();// Load device info for server identification+ debugPrint('[Init] device info... (${sw.elapsedMilliseconds}ms)');await ApiService.initDeviceId();await ApiService.initVersion();try {@@ -297,27 +318,25 @@ class _AuthGateState extends State<AuthGate> {ApiService.deviceSdkInt = info.version.sdkInt;} catch (_) {}- // Initialize log service (must be before other services so debugPrint is captured)- try {- final loggingEnabled = await PlayerSettings.getLoggingEnabled();- await LogService().init(loggingEnabled);- } catch (_) {}-// Downloads must be loaded before the audio handler so getChildren()// can serve the Android Auto browse tree immediately.+ debugPrint('[Init] DownloadService... (${sw.elapsedMilliseconds}ms)');try {await DownloadService().init().timeout(const Duration(seconds: 8));} catch (e) {debugPrint('[Init] DownloadService.init timed out or failed: $e');}+ debugPrint('[Init] DownloadService done (${sw.elapsedMilliseconds}ms)');// Timeout guards against AudioService.init() hanging when Android killed// the app process but kept the MediaBrowserService alive.+ debugPrint('[Init] AudioPlayerService... (${sw.elapsedMilliseconds}ms)');try {await AudioPlayerService.init().timeout(const Duration(seconds: 8));} catch (e) {debugPrint('[Init] AudioPlayerService.init timed out or failed: $e');}+ debugPrint('[Init] AudioPlayerService done (${sw.elapsedMilliseconds}ms)');try {await DownloadNotificationService().init();@@ -339,6 +358,7 @@ 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();@@ -351,6 +371,7 @@ class _AuthGateState extends State<AuthGate> {} catch (e) {debugPrint('[Init] Service init failed: $e');}+ debugPrint('[Init] _initServices complete (${sw.elapsedMilliseconds}ms)');}@overridediff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex 79bd1520..ec5bc693 100644--- a/lib/providers/auth_provider.dart+++ b/lib/providers/auth_provider.dart@@ -52,17 +52,23 @@ class AuthProvider extends ChangeNotifier {/// Try to restore a saved session from SharedPreferences./// If the server is unreachable, still restore credentials so offline mode works.Future<void> tryRestoreSession() async {+ final sw = Stopwatch()..start();+ debugPrint('[Auth] tryRestoreSession started');_isLoading = true;_serverReachable = true;notifyListeners();try {+ debugPrint('[Auth] getting SharedPreferences...');final prefs = await SharedPreferences.getInstance();+ debugPrint('[Auth] SharedPreferences loaded (${sw.elapsedMilliseconds}ms)');final savedUrl = prefs.getString('server_url');final savedToken = prefs.getString('token');final savedUsername = prefs.getString('username');final savedLibraryId = prefs.getString('default_library_id');+ debugPrint('[Auth] saved credentials: url=${savedUrl != null}, token=${savedToken != null}');+if (savedUrl != null && savedToken != null) {// Always restore credentials so we can at least go offline_serverUrl = savedUrl;@@ -80,26 +86,32 @@ class AuthProvider extends ChangeNotifier {}// Check if server is actually reachable+ debugPrint('[Auth] pinging server... (${sw.elapsedMilliseconds}ms)');final reachable = await ApiService.pingServer(savedUrl, customHeaders: _customHeaders);_serverReachable = reachable;+ debugPrint('[Auth] ping result: reachable=$reachable (${sw.elapsedMilliseconds}ms)');// Fetch full user info (needed for isAdmin, permissions, etc.)if (reachable) {try {+ debugPrint('[Auth] fetching /me... (${sw.elapsedMilliseconds}ms)');final api = ApiService(baseUrl: savedUrl, token: savedToken, customHeaders: _customHeaders);final me = await api.getMe();if (me != null) {_userJson = me;_userId = me['id'] as String?;}+ debugPrint('[Auth] /me done (${sw.elapsedMilliseconds}ms)');} catch (_) {}}}- } catch (_) {+ } catch (e) {// Restore failed — but if we already set credentials, keep them+ debugPrint('[Auth] tryRestoreSession error: $e (${sw.elapsedMilliseconds}ms)');_serverReachable = false;}+ debugPrint('[Auth] tryRestoreSession done, isAuthenticated=$isAuthenticated (${sw.elapsedMilliseconds}ms)');_isLoading = false;notifyListeners();}diff --git a/pubspec.yaml b/pubspec.yamlindex 3733e3cf..815d9265 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: A Material 3 Audiobookshelf client for Android.publish_to: 'none'-version: 1.8.5+35+version: 1.8.6+36environment:sdk: '>=3.1.0 <4.0.0'