Implementing App State Management
1. Detecting App State Changes
| Event | Description | Notes |
|---|---|---|
| appStateChange | Triggered when the app state changes (e.g., foreground, background) | Available in Ionic 7+ |
| pause | Emitted when the app is paused (e.g., user navigates away) | Standard Cordova/PhoneGap event |
| resume | Emitted when the app resumes from a paused state | Standard Cordova/PhoneGap event |
Example: Listening to App State Changes
import { App } from '@ionic/angular';
App.addListener('appStateChange', (state) => {
console.log('App state changed to:', state);
});
App.addListener('pause', () => {
console.log('App paused');
});
App.addListener('resume', () => {
console.log('App resumed');
});
Note: The
appStateChange event provides more granular information about the app state, including whether it is in the foreground or background.2. Handling Foreground State
| Property | Description | Usage |
|---|---|---|
| appState | Represents the current state of the application (foreground, background) | import { App } from '@ionic/angular'; |
| isForeground | Boolean indicating if the app is in foreground state | App.isForeground() |
Example: Detecting App State Changes
import { App } from '@ionic/angular';
App.addListener('appStateChange', (state) => {
if (state.isActive) {
console.log('App is in foreground');
} else {
console.log('App is in background');
}
});
Note: The
appStateChange event is emitted whenever the app state changes between foreground and background.3. Handling Background State
| Property | Description | Usage |
|---|---|---|
| backgroundState | Indicates whether the app is running in background mode | backgroundState: boolean |
Example: Detecting Background State
import { App } from '@ionic/angular';
App.addListener('appStateChange', (state) => {
console.log('App is in background:', state.isActive);
});
Note: The
appStateChange event fires when the app transitions between active and inactive states.
Key Points
- isActive property indicates foreground state
- Use
appStateChangefor real-time background detection - Can be used to pause/resume operations based on app state
4. Using App Resume Event
The app resume event in Ionic is triggered when the application comes back to the foreground after being in the background. This event is particularly useful for managing app state, such as refreshing data or resuming ongoing operations.
| Event | Description | Usage |
|---|---|---|
| ionAppResume | Emitted when the app resumes from background state. | Use to refresh data or resume operations. |
Example: Handling App Resume
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Platform } from '@ionic/angular';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss']
})
export class HomePage implements OnInit, OnDestroy {
constructor(private platform: Platform) {}
ngOnInit() {
this.platform.ready().then(() => {
this.platform.resume.subscribe(() => {
console.log('App resumed');
// Refresh data or resume operations here
});
});
}
ngOnDestroy() {
this.platform.resume.unsubscribe();
}
}
Note: The
ionAppResume event is part of the Ionic Platform API and is not available in all environments (e.g., web browsers). It is primarily used in native mobile app environments.
5. Implementing Background Tasks
| Task Type | Description | Implementation | Notes |
|---|---|---|---|
| Background Task | Long-running operations that continue when app is in background | BackgroundTask API or WorkManager |
Use for data sync, file uploads, etc. |
| Push Notifications | Receive and process messages while app is closed | Firebase Cloud Messaging (FCM) |
Requires server-side setup and permissions |
| Local Notifications | Schedule and trigger notifications from app | @ionic-native/local-notifications |
Works even when app is not running |
Example: Schedule a Local Notification
import { LocalNotifications } from '@ionic-native/local-notifications/ngx';
LocalNotifications.schedule({
id: 1,
title: 'Reminder',
text: 'Time for your daily task',
trigger: { at: new Date().setHours(9, 0, 0, 0) }
});
Note: Background tasks in mobile apps are limited by platform restrictions (iOS/Android). Ensure proper permissions and lifecycle handling.
6. Managing App Lifecycle
| Event | Description | Usage |
|---|---|---|
| ionAppLoad | Triggered when the app is fully loaded and ready | document.addEventListener('ionAppLoad', () => { console.log('App loaded'); }); |
| ionViewDidEnter | Triggered when a view enters and becomes active | this.router.events.subscribe((event) => { if (event instanceof NavigationEnd) { console.log('View entered'); } }); |
| ionViewWillLeave | Triggered before a view is about to leave | ionViewWillLeave() { console.log('Preparing to leave view'); } |
| ionViewDidLeave | Triggered after a view has left | ionViewDidLeave() { console.log('View has left'); } |
| ionPause | Triggered when the app is paused (e.g., user switches to another app) | document.addEventListener('ionPause', () => { console.log('App paused'); }); |
| ionResume | Triggered when the app resumes from a paused state | document.addEventListener('ionResume', () => { console.log('App resumed'); }); |
Example: Handling App Lifecycle Events
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html'
})
export class HomePage {
constructor() {
document.addEventListener('ionPause', () => {
console.log('App paused');
});
document.addEventListener('ionResume', () => {
console.log('App resumed');
});
}
}
Note: Use
ionViewDidEnter and ionViewDidLeave for view-specific lifecycle management.
Warning: Avoid heavy operations in
ionPause and ionResume as they can affect app responsiveness.
7. Handling App Terminate
| Method | Description | Notes |
|---|---|---|
| handleAppTerminate() | Callback function to manage app termination logic | Used in conjunction with App plugin for lifecycle events |
Example: Handling App Termination
import { App } from '@capacitor/app';
App.addListener('appTerminate', (info) => {
console.log('App terminated', info);
// Save app state or clean up resources here
});
// Optional: Clear listeners when component unmounts
// App.removeAllListeners();
Note: The
appTerminate event is emitted when the app is closed or terminated. It's useful for saving state or cleaning up resources before the app exits.8. Using App URLs
| Property | Description | Usage |
|---|---|---|
| appUrl | URL used to launch the app | AppUrl is available via IonicApp component |
| url | Current app URL | Can be accessed via Router or NavController |
Example: Accessing App URL
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController) {}
ionViewDidLoad() {
console.log('Current URL:', this.navCtrl.getActive().url);
}
}
Note: App URLs are useful for deep linking and navigation within the app.
Warning: Ensure that URL paths are properly encoded to avoid navigation issues.
9. Detecting App Launch URL
| Property | Description | Usage |
|---|---|---|
| launchUrl | URL used to launch the app | import { Plugins } from '@capacitor/core'; const { App } = Plugins; console.log(App.launchUrl); |
Example: Retrieving Launch URL
import { Plugins } from '@capacitor/core';
const { App } = Plugins;
console.log("App launched with URL: ", App.launchUrl);
Note: The launch URL is only available on native platforms (iOS, Android) and not in web browsers.
10. Implementing State Restoration
| Property | Description | Default | Notes |
|---|---|---|---|
| stateKey | Unique identifier for the state to be restored | null |
Used in combination with stateStorage to persist and restore state |
| stateStorage | Storage mechanism to use for persisting state (e.g., localStorage, sessionStorage) |
localStorage |
Can be customized to use custom storage logic |
Example: Basic State Restoration Setup
import { IonicApp } from 'ionic-angular';
IonicApp.forRoot({
stateKey: 'myApp',
stateStorage: localStorage
});
Note: State restoration is particularly useful in hybrid apps where users expect their app to remember the last viewed screen or form data after a restart.