Overview
This lecture covers the Expo Background Task module, explaining how to run logic when your app is not open, including setup, use cases, constraints, and implementation in a React Native app.
Background Tasks: Concepts & Constraints
- Background tasks allow apps to run custom logic when not in the foreground (e.g., prefetch data, sync, OTA updates).
- Tasks can be scheduled with a minimum interval of 15 minutes, but iOS often schedules them less frequently (like overnight).
- Task execution depends on device state (network, battery, user activity) and may be skipped if resources are low.
- Users can disable background refresh or kill the app, which stops background tasks.
- Best practices: keep tasks light, batch operations, avoid heavy processing.
Use Cases & Examples
- Sync user data, backup, upload logs, or download updates automatically.
- Prefetch content to ensure fast load times when users return to the app.
- The demo app fetches and saves daily quotes in the background for instant display.
Setup & Dependencies
- Install dependencies:
expo install react-native-async-storage, expo-task-manager, expo-background-task
.
- Configure Expo for iOS/Android; Expo background task depends on Expo Task Manager.
- Only test on real iOS devices; Android emulators support background tasks.
Implementation Steps
- Define constants: task identifier, minimum interval (e.g., 15 min), async storage key, and maximum history size.
- Create TypeScript types for quotes and quote history.
- Implement core functions:
initializeBackgroundTask
: registers background task and ensures it runs only after app JS loads.
- Background task logic: fetches a quote, adds a timestamp, maintains a max history, and stores it.
- Use an “inner app mounted” promise to ensure AsyncStorage is accessible.
- Use React hooks to call initialization, load stored quotes, and set up state.
- Display quote history in the UI.
- Add a debug button to manually trigger background tasks for testing.
- Use AppState to detect when the app returns to foreground and reload quote history.
- Clean up AppState subscriptions on component unmount.
Key Terms & Definitions
- Background Task — A process running logic while the app is in the background.
- AsyncStorage — Local persistent storage for React Native apps.
- Expo Task Manager — Expo module for managing long-running/background tasks.
- AppState — React Native API to track app foreground/background status.
- Minimum Interval — Shortest possible time between background task executions (15 min).
Action Items / Next Steps
- Review Expo Background Task and Task Manager documentation.
- Test background tasks on a real iOS device.
- Clean up AppState event listeners when components unmount.