跳转到正文

快速入门

GitHub

@capgo/capacitor-background-task 允许 Capacitor 应用注册命名周期任务,用于同步、缓存刷新、分析数据上报及其他后台获取操作。

你可以使用我们的 AI 辅助设置来安装插件。使用以下命令将 Capgo skills 添加到你的 AI 工具中:

终端窗口
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

然后使用以下 prompt:

Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-background-task` plugin in my project.

如果你更想手动设置,请运行以下命令安装插件,并按照下方各平台的说明操作:

终端窗口
npm install @capgo/capacitor-background-task
npx cap sync

将后台处理模式和允许的任务标识符添加到 ios/App/App/Info.plist:

<key>UIBackgroundModes</key>
<array>
<string>processing</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>app.capgo.backgroundtask.processing</string>
</array>

然后运行:

终端窗口
npx cap sync ios
import { BackgroundTask, BackgroundTaskResult } from '@capgo/capacitor-background-task';
  • 模块作用域:注册 defineTask 在……之前 registerTaskAsync.
  • iOS ID:匹配 BGTaskSchedulerPermittedIdentifiers 条目。
  • 间隔:系统可能会延迟任务执行,超过 minimumInterval.

在模块作用域中定义回调,以便在操作系统启动应用时立即注册。

import { BackgroundTask, BackgroundTaskResult } from '@capgo/capacitor-background-task';
const SYNC_TASK = 'sync-offline-data';
BackgroundTask.defineTask(SYNC_TASK, async () => {
try {
await fetch('https://api.example.com/sync', { method: 'POST' });
return BackgroundTaskResult.Success;
} catch {
return BackgroundTaskResult.Failed;
}
});

调用 registerTaskAsync 在应用拥有足够上下文以启用后台任务之后。

await BackgroundTask.registerTaskAsync(SYNC_TASK, {
minimumInterval: 30,
requiresNetwork: true,
});

minimumInterval 单位为分钟。Android 强制最小间隔为 15 分钟。iOS 将该值视为最早开始时间,实际执行可能会更晚。

const status = await BackgroundTask.getStatusAsync();
const isRegistered = await BackgroundTask.isTaskRegisteredAsync(SYNC_TASK);
const registeredTasks = await BackgroundTask.getRegisteredTasksAsync();
console.log({ status, isRegistered, registeredTasks });

在开发或 QA 环境中使用测试触发器。它会立即调用所有已注册的任务。

await BackgroundTask.triggerTaskWorkerForTestingAsync();
await BackgroundTask.unregisterTaskAsync(SYNC_TASK);

iOS 可能会在 JavaScript 任务完成前停止后台任务。当需要清理或检查点时,请监听过期事件。

const expiration = await BackgroundTask.addExpirationListener((event) => {
console.warn('Background task expired', event.taskName, event.taskId);
});
await expiration.remove();

该插件还为从以下应用迁移的用户提供了一个小型兼容层: react-native-background-task.

import { BackgroundTask } from '@capgo/capacitor-background-task';
BackgroundTask.define(async () => {
await fetch('https://api.example.com/sync', { method: 'POST' });
});
await BackgroundTask.schedule({
period: 1800,
});
  • 后台调度是机会性的,而非精确的。
  • 保持任务简短且幂等。
  • 在返回前持久化任何所需的状态 BackgroundTaskResult.Success.
  • 避免依赖后台任务来处理用户可见的截止日期或闹钟。

如果你正在使用 快速入门 要规划原生插件工作,请将其与 使用 @capgo/capacitor-background-task 用于“使用 @capgo/capacitor-background-task”中的原生能力, Capgo 插件目录 查看 Capgo 插件目录中的产品工作流, Capgo 提供的 Capacitor 插件 查看由 Capgo 提供的 Capacitor 插件中的实现细节, 添加或更新插件 关于“添加或更新插件”中的实现细节,以及 Ionic Enterprise 插件替代方案 关于“Ionic Enterprise 插件替代方案”中的产品工作流。