首页指南参考教程

Expo TaskManager

为可以在后台运行的任务提供支持的库。

Android
iOS

expo-task-manager 提供了一个 API,允许你管理长时间运行的任务,特别是那些可以在你的应用在后台运行时运行的任务。此库的某些功能由其他库在后台使用。以下是使用 TaskManager 的 Expo SDK 库列表:

¥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 library are used by other libraries under the hood. Here is a list of Expo SDK libraries that use TaskManager:

  • 定位

    ¥Location

  • BackgroundFetch

  • 通知

    ¥Notifications

安装

¥Installation

Terminal
npx expo install expo-task-manager

If you are installing this in an existing React Native app (bare workflow), start by installing expo in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.

app.json/app.config.js 中的配置

¥Configuration in app.json/app.config.js

iOS 上的后台模式

¥Background modes on iOS

TaskManager 在 Android 上的 Expo Go 应用中开箱即用。但是,在 iOS 上,你需要使用 开发构建

¥TaskManager works out of the box in the Expo Go app on Android. However, on iOS, you'll need to use a development build.

独立应用需要一些额外的配置:在 iOS 上,每个后台功能都需要 Info.plist 文件中 UIBackgroundModes 数组中的特殊键。在独立应用中,该数组默认为空,因此要使用后台功能,你需要向 app.json 配置添加适当的键。

¥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 to use background features you will need to add appropriate keys to your app.json configuration.

以下是启用后台位置、后台获取和远程通知的 app.json 配置示例:

¥Here is an example of an app.json configuration that enables background location, background fetch and remote notifications:

app.json
{
  "expo": {
    "ios": {
      "infoPlist": {
        "UIBackgroundModes": ["location", "fetch", "remote-notification"]
      }
    }
  }
}
Are you using this library in a bare React Native app?

了解如何在 expo-task-manager 存储库中的安装说明 文件中配置原生项目。

¥Learn how to configure the native projects in the installation instructions in the expo-task-manager repository.

示例

¥Example

Example
import React from 'react';
import { Button, View, StyleSheet } from 'react-native';
import * as TaskManager from 'expo-task-manager';
import * as Location from 'expo-location';

const LOCATION_TASK_NAME = 'background-location-task';

const requestPermissions = async () => {
  const { status: foregroundStatus } = await Location.requestForegroundPermissionsAsync();
  if (foregroundStatus === 'granted') {
    const { status: backgroundStatus } = await Location.requestBackgroundPermissionsAsync();
    if (backgroundStatus === 'granted') {
      await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
        accuracy: Location.Accuracy.Balanced,
      });
    }
  }
};

const PermissionsButton = () => (
  <View style={styles.container}>
    <Button onPress={requestPermissions} title="Enable background location" />
  </View>
);

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
  }
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default PermissionsButton;

API

import * as TaskManager from 'expo-task-manager';

Methods

TaskManager.defineTask<T>(taskName, taskExecutor)

NameTypeDescription
taskNamestring

Name of the task. It must be the same as the name you provided when registering the task.

taskExecutorTaskManagerTaskExecutor<T>

A function that will be invoked when the task with given taskName is executed.


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.

Returns:

void

TaskManager.getRegisteredTasksAsync()

Provides information about tasks registered in the app.

Returns:

Promise<TaskManagerTask[]>

A promise which fulfills with an array of tasks registered in the app. Example:

[
  {
    taskName: 'location-updates-task-name',
    taskType: 'location',
    options: {
      accuracy: Location.Accuracy.High,
      showsBackgroundLocationIndicator: false,
    },
  },
  {
    taskName: 'geofencing-task-name',
    taskType: 'geofencing',
    options: {
      regions: [...],
    },
  },
]

TaskManager.getTaskOptionsAsync<TaskOptions>(taskName)

NameTypeDescription
taskNamestring

Name of the task.


Retrieves options associated with the task, that were passed to the function registering the task (eg. Location.startLocationUpdatesAsync).

Returns:

Promise<TaskOptions>

A promise which fulfills with the options object that was passed while registering task with given name or null if task couldn't be found.

TaskManager.isAvailableAsync()

Determine if the TaskManager API can be used in this app.

Returns:

Promise<boolean>

A promise fulfills with true if the API can be used, and false otherwise. On the web it always returns false.

TaskManager.isTaskDefined(taskName)

NameTypeDescription
taskNamestring

Name of the task.


Checks whether the task is already defined.

Returns:

boolean

TaskManager.isTaskRegisteredAsync(taskName)

NameTypeDescription
taskNamestring

Name of the task.


Determine whether the task is registered. Registered tasks are stored in a persistent storage and preserved between sessions.

Returns:

Promise<boolean>

A promise which fulfills with a boolean value whether or not the task with given name is already registered.

TaskManager.unregisterAllTasksAsync()

Unregisters all tasks registered for the running app. You may want to call this when the user is signing out and you no longer need to track his location or run any other background tasks.

Returns:

Promise<void>

A promise which fulfills as soon as all tasks are completely unregistered.

TaskManager.unregisterTaskAsync(taskName)

NameTypeDescription
taskNamestring

Name of the task to unregister.


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.

Returns:

Promise<void>

A promise which fulfills as soon as the task is unregistered.

Interfaces

TaskManagerError

Error object that can be received through TaskManagerTaskBody when the task fails.

TaskManagerError Properties

NameTypeDescription
codestring | number-
messagestring-

TaskManagerTask

Represents an already registered task.

TaskManagerTask Properties

NameTypeDescription
optionsany

Provides options that the task was registered with.

taskNamestring

Name that the task is registered with.

taskTypestring

Type of the task which depends on how the task was registered.


TaskManagerTaskBody

Represents the object that is passed to the task executor.

TaskManagerTaskBody Properties

NameTypeDescription
dataT

An object of data passed to the task executor. Its properties depends on the type of the task.

errornull | TaskManagerError

Error object if the task failed or null otherwise.

executionInfoTaskManagerTaskBodyExecutionInfo

Additional details containing unique ID of task event and name of the task.


TaskManagerTaskBodyExecutionInfo

Additional details about execution provided in TaskManagerTaskBody.

TaskManagerTaskBodyExecutionInfo Properties

NameTypeDescription
appState
(optional)
'active' | 'background' | 'inactive'
Only for:
iOS

State of the application.

eventIdstring

Unique ID of task event.

taskNamestring

Name of the task.


Types

TaskManagerTaskExecutor()

Type of task executor – a function that handles the task.

NameType
bodyTaskManagerTaskBody<T>
Expo 中文网 - 粤ICP备13048890号