App Lifecycle Protector

An event-driven lifecycle scheduler and business logic orchestrator for Flutter.

Pub Version License: MIT

๐Ÿ“ธ Key Features & UI

1. Authorization on Launch 2. Biometric Fallback 3. Semantic Activity Tracking
Start Lock Fallback Home
Locks the app immediately upon startup. Seamlessly transitions to passphrase. Updates "alive" status on interaction.

๐ŸŒŸ Why this package?

Flutter's built-in AppLifecycleListener is great for simple state changes, but it lacks high-level abstractions for complex background tasks and security. This package is built as an Event-Driven Orchestrator:

  • Smart onPeriodic Polling: A resource-friendly inspection loop that runs only when the app is visible. It automatically pauses in the background, preventing unnecessary CPU/battery drainโ€”ideal for network monitoring or scheduled API tasks.
  • Decoupled Logic: Move complex lifecycle logic (like heartbeats, data refreshes, or security checks) out of your Widgets and into a clean, testable AppLifecycleEvent class.
  • Graceful Exit Handling: Override onExitRequested() to intercept app shutdown and perform cleanup before exit, such as closing database connections or saving app state.
  • Semantic UI Overlays: Effortlessly toggle "Mask" (privacy) and "Lock" (authorization) states across your entire application.

๐Ÿš€ Quick Start

1. Define Your Logic (Business + Security)

Extend AppLifecycleEvent to handle periodic tasks and state changes in one place.

class MySmartHandler extends AppLifecycleEvent {
  final ScreenSecure screenSecure;
  MySmartHandler(this.screenSecure);

  @override
  void onPeriodic() {
    // This runs every 10s ONLY when the app is visible
    // 1. Business Logic: e.g., Check network or fetch notifications
    print("Performing resource-friendly API polling...");

    // 2. Security Logic: e.g., Idle timeout check
    if (!AppLifecycleScheduler.instance.isAlive()) {
      screenSecure.lock(); 
    }
  }

  @override
  Future<AppExitResponse> onExitRequested() async {
    print('App Exit...');
    return AppExitResponse.exit;
  }

}

2. Initialize in the Root Widget

Initialize the scheduler in your root widget's initState to ensure it's ready before the UI builds.

@override
void initState() {
  super.initState();
  
  AppLifecycleScheduler.initialize(
    interval: const Duration(seconds: 10), // Inspection frequency
    event: MySmartHandler(screenSecure), // Your custom logic
  );

  // Set idle timeout (e.g., 5 minutes)
  AppLifecycleScheduler.instance.aliveDuration = const Duration(minutes: 5);
}

3. Wrap Your Application

Use ScreenProtector in your MaterialApp.builder to protect all routes.

MaterialApp(
  builder: (context, child) {
    return ScreenProtector(
      screenSecure: screenSecure,
      lockWidget: MyGlobalLockScreen(),
      child: child!, // Wraps the entire Navigator stack
    );
  },
  home: const MyHomePage(),
)

๐Ÿ› ๏ธ Implementation Patterns

Automatic App Lock on Launch

To ensure the app starts in a protected state, simply call lock() during initialization:

@override
void initState() {
  super.initState();
  // ... initialization ...
  screenSecure.lock(); // Immediate lock
}

Privacy Masking

Automatically protect the UI snapshot in the multitasking view.

@override
void onPause() {
  screenSecure.mask(); // Shows maskWidget
}

@override
void onResume() {
  screenSecure.unmask(); // Hides maskWidget
}

๐Ÿ“„ Documentation & Support

Real-world Implementation

app_lifecycle_protector is not just a theoretical component; it has been deeply battle-tested in ChaBox, the core application of the ChaCrypt ecosystem.

ChaCrypt is an offline file encryption/decryption ecosystem based on the ChaCha20-Poly1305 standard, and ChaBox is its graphical offline file security workstation. In ChaBox, we utilize this component to build a comprehensive Active Defense system:

  • App Lock: Controls access after launch, ensuring the app can only be used after your authorization.
  • Idle Lock: Automatically triggers a lock if the app remains inactive for a period after login.
  • Anti-Screenshot/Recording: Provides software-level protection against other malicious apps on the same device capturing or recording the screen.
  • Screen Masking: Triggers a privacy mask during app switching (mobile) to prevent sensitive information leakage.

If you are looking for how to integrate these security features into a complex, production-grade application, ChaBox serves as an excellent reference. Visit the ChaCrypt GitHub repository to learn more.

Support the Project ๐Ÿ’–

If you find this package useful and would like to see it continue to improve and evolve, please consider showing your support:

  • โญ Star the Repo: Give it a Star on GitHub or a Like on pub.dev.
  • โ˜• Support the Developer (Global): Support via GitHub Sponsors or Buy Me a Coffee.
  • ๐Ÿผ Support via Ifdian (Mainland China): Users in China can also show support via Ifdian.

Thank you for your support, which is a vital boost that keeps me focused on the project's continuous iteration; because of you, more people can benefit from this tool much sooner.

License

MIT License.