app_lifecycle_manager.dart 1.6 KB

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