DEV Community

HarmonyOS
HarmonyOS

Posted on

Does AbilityStage Survive Ability Restarts? Lifecycle Deep Dive

Read the original article:Does AbilityStage Survive Ability Restarts? Lifecycle Deep Dive

Context

Developers working with HarmonyOS Stage model often initialize shared state or services in AbilityStage, expecting it to persist throughout the app’s lifecycle. However, they encounter cases where the state is unexpectedly lost after restarting abilities or switching between UIAbility and ExtensionAbility.

Description

AbilityStage serves as the application-level entry point in Stage model HarmonyOS apps. It’s created per process, and its onCreate() is invoked when that process is started.

A common question is: "Will my AbilityStage survive when I close and reopen an ability?"

The answer depends on whether the underlying process remains alive. When the process survives, AbilityStage also persists. But if the process is killed (e.g., by system memory reclamation, a crash, or user force-stop), the entire context, including AbilityStage, is lost and recreated.

Solution

To handle AbilityStage lifecycle properly:

  • Do not treat AbilityStage like a persistent singleton — it can be recreated multiple times across the app’s lifetime.

  • Store essential state in persistent storage (e.g., Preferences, Database, or Files).

  • Use ApplicationContext to register and reinitialize services each time AbilityStage.onCreate() is triggered.

  // Example: Initializing a service or shared state in AbilityStage
  export default class MyAbilityStage extends AbilityStage {
    onCreate() {
      console.info('AbilityStage created');

      // Load persistent data
      const data = AppStorage.get<number>('launchCount') ?? 0;
      AppStorage.setOrCreate('launchCount', data + 1);

      // Initialize services
      ServiceContainer.set(NetworkManager, new NetworkManager(this.context.getApplicationContext()));

      // Or Initialize global instances
      MediaController.initialize(this.context.getApplicationContext())
    }
  }
Enter fullscreen mode Exit fullscreen mode
  • Be mindful that different component types (UIAbility, FormExtensionAbility, etc.) may run in separate processes, each having its own AbilityStage.

  • If using in-memory caching, ensure rehydration from persistent sources when AbilityStage is recreated.

Key Takeaways

  • AbilityStage survives only if the process is alive.
  • Restarting an Ability alone does not kill AbilityStage — unless the process is also terminated.
  • Each process gets a separate AbilityStage instance.
  • Avoid storing critical state solely in memory within AbilityStage.
  • Always account for multi-process behavior in HarmonyOS Stage model.

Additional Resources

AbilityStage Official Guide – HarmonyOS Developer

Process Model in Stage Model – HarmonyOS Docs

Written by Bilal Basboz

Top comments (0)