跳过内容

Getting Started

@capgo/capacitor-background-task 让一个 Capacitor 应用程序注册周期性任务来同步、缓存刷新、分析数据传递和其他后台抓取操作。

终端窗口
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';

定义一个任务

定义任务

定义回调函数在模块范围内,以便在操作系统启动应用程序时立即注册。

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 需要 __CAPGO_KEEP_0__ 分钟。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);

__CAPGO_KEEP_0__

iOS 过期

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.
  • 避免依赖后台任务来处理用户可见的截止日期或闹钟

从 Getting Started 继续

标题:从 Getting Started 继续

如果您正在使用 Getting Started 来规划原生插件工作,连接它到 使用 @capgo/capacitor-background-task 为原生能力在使用 @capgo/capacitor-background-task 中 Capgo Plugin Directory 为产品工作流程在 Capgo Plugin Directory 中 Capacitor Plugins by Capgo for the implementation detail in Capacitor Plugins by Capgo, 添加或更新插件 为添加或更新插件的实现细节提供详细信息, Ionic 企业插件替代方案 为 Ionic 企业插件替代方案的产品工作流程提供详细信息。