app_lifecycle_manager.dart 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import 'package:flutter/material.dart';
  2. import '../game/zentap_game.dart';
  3. import '../game/audio/audio_manager.dart';
  4. /// Manages app lifecycle events for game suspension and resumption
  5. class AppLifecycleManager with WidgetsBindingObserver {
  6. static AppLifecycleManager? _instance;
  7. ZenTapGame? _currentGame;
  8. AppLifecycleManager._();
  9. static AppLifecycleManager get instance {
  10. _instance ??= AppLifecycleManager._();
  11. return _instance!;
  12. }
  13. /// Initialize the lifecycle manager
  14. void initialize() {
  15. WidgetsBinding.instance.addObserver(this);
  16. }
  17. /// Dispose the lifecycle manager
  18. void dispose() {
  19. WidgetsBinding.instance.removeObserver(this);
  20. _currentGame = null;
  21. }
  22. /// Register the current active game instance
  23. void setCurrentGame(ZenTapGame? game) {
  24. _currentGame = game;
  25. }
  26. /// Get the current active game instance
  27. ZenTapGame? getCurrentGame() {
  28. return _currentGame;
  29. }
  30. @override
  31. void didChangeAppLifecycleState(AppLifecycleState state) {
  32. super.didChangeAppLifecycleState(state);
  33. // Handle app lifecycle changes for game suspension and audio management
  34. switch (state) {
  35. case AppLifecycleState.resumed:
  36. // App came back to foreground, resume game if there's an active game
  37. _currentGame?.resumeGame();
  38. // Resume background music if enabled
  39. AudioManager().resumeBackgroundMusic();
  40. break;
  41. case AppLifecycleState.inactive:
  42. case AppLifecycleState.paused:
  43. // App went to background, screen turned off
  44. // Suspend the game to save battery and resources
  45. _currentGame?.pauseGame();
  46. // Pause background music to save battery
  47. AudioManager().pauseBackgroundMusic();
  48. break;
  49. case AppLifecycleState.detached:
  50. case AppLifecycleState.hidden:
  51. // App is being closed or hidden
  52. // Stop all audio immediately
  53. AudioManager().stopBackgroundMusic();
  54. _currentGame?.pauseGame();
  55. break;
  56. }
  57. }
  58. }