expo-task-manager provides an API that allows you to manage long-running tasks, in particular those tasks that can run while your app is in the background.
Some features of this module are used by other modules under the hood. Here is a list of Expo modules that use TaskManager:
TaskManager works out of the box in the Expo client on Android, but on iOS you'll need to test using a custom Expo client.
Standalone apps need some extra configuration: on iOS, each background feature requires a special key in UIBackgroundModes array in your Info.plist file. In standalone apps this array is empty by default, so in order to use background features you will need to add appropriate keys to your app.json configuration.
Here is an example of an app.json configuration that enables background location and background fetch:
For bare React Native apps, you need to add those keys manually. You can do it by clicking on your project in Xcode, then Signing & Capabilities, adding the BackgroundMode capability (if absent), and checking either Location updates or Background fetch, depending on your needs.
Defines task function.
It must be called in the global scope of your JavaScript bundle. In particular, it cannot be called in any of React lifecycle methods like componentDidMount.
This limitation is due to the fact that when the application is launched in the background, we need to spin up your JavaScript app, run your task and then shut down — no views are mounted in this scenario.
Unregisters task from the app, so the app will not be receiving updates for that task anymore.
It is recommended to use methods specialized by modules that registered the task, eg. Location.stopLocationUpdatesAsync.
importReactfrom'react';import{Text,TouchableOpacity}from'react-native';import*asTaskManagerfrom'expo-task-manager';import*asLocationfrom'expo-location';constLOCATION_TASK_NAME='background-location-task';exportdefaultclassComponentextendsReact.Component{onPress=async()=>{const{ status }=awaitLocation.requestPermissionsAsync();if(status ==='granted'){awaitLocation.startLocationUpdatesAsync(LOCATION_TASK_NAME,{
accuracy:Location.Accuracy.Balanced,});}};render(){return(<TouchableOpacity onPress={this.onPress}><Text>Enable background location</Text></TouchableOpacity>);}}TaskManager.defineTask(LOCATION_TASK_NAME,({ data, error })=>{if(error){// Error occurred - check `error.message` for more details.return;}if(data){const{ locations }= data;// do something with the locations captured in the background}});