使用 @capgo/capacitor-background-task
在具有命名任务、持久注册、状态检查、注销和开发触发器的 Capacitor 应用中,定期在后台执行 fetch 工作。该插件使用 Android WorkManager 和 iOS BGTaskScheduler。
安装
npm install @capgo/capacitor-background-task
npx cap sync
iOS 配置
添加背景处理支持到 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
此插件暴露的内容
defineTask- 为命名任务定义 JavaScript 回调。registerTaskAsync- 持久和定期执行一个任务。unregisterTaskAsync- 取消一个任务。isTaskRegisteredAsync- 检查一个任务的注册状态。getRegisteredTasksAsync- 已注册的任务名称列表.getStatusAsync- 检查本地后台任务可用性.triggerTaskWorkerForTestingAsync- 为开发目的立即触发已注册的任务.addExpirationListener- iOS过期任务时的回调函数.
Example Usage
在模块范围内定义任务,以便在应用程序唤醒时可用:
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;
}
});
await BackgroundTask.registerTaskAsync(SYNC_TASK, {
minimumInterval: 30,
requiresNetwork: true,
});
检查状态和已注册的任务名称:
const status = await BackgroundTask.getStatusAsync();
const tasks = await BackgroundTask.getRegisteredTasksAsync();
console.log({ status, tasks });
触发开发运行:
await BackgroundTask.triggerTaskWorkerForTestingAsync();
取消任务:
await BackgroundTask.unregisterTaskAsync(SYNC_TASK);
Platform Notes
- 后台任务的调度是机会主义的,而不是精确的定时器.
- Android周期性工作有15分钟的最小间隔.
- iOS 视为最早的开始日期,并可能在此之后运行。
minimumInterval在物理设备上测试 iOS 后台处理。 - 全参考
__CAPGO_KEEP_0__:
- https://GitHub.com/Cap-go/__CAPGO_KEEP_1__-background-task/ https://github.com/Cap-go/capacitor-background-task/
- 从使用 @__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-background-task 继续。
Keep going from Using @capgo/capacitor-background-task
使用 @__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-background-task Using @capgo/capacitor-background-task @__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-background-task 使用 @capgo/capacitor-background-task 为 @capgo/capacitor-background-task 的实现细节, 开始使用 为开始使用的实现细节, Capgo 插件目录 为 Capgo 插件目录中的产品工作流程, Capacitor 由 Capgo 提供的插件 为 Capacitor 由 Capgo 提供的插件的实现细节, 和 添加或更新插件 为添加或更新插件的实现细节。