@capacitor/background-runner
后台运行器提供了一个基于事件的独立 JavaScript 环境,用于在 WebView 之外执行您的 JavaScript 代码。
安装
npm install @capacitor/background-runner
npx cap sync
后台运行器支持多种设备 API,这些 API 在使用前需要用户授权。
iOS
在 iOS 上,您必须启用后台模式能力。
添加后,您至少需要启用 Background fetch
和 Background processing
模式,以便能够注册和调度后台任务。
如果您将使用地理位置或推送通知,请分别启用 Location updates
或 Remote notifications
。
启用后台模式能力后,将以下内容添加到您的应用程序的 AppDelegate.swift
中:
在文件顶部,import Capacitor
下方添加:
import CapacitorBackgroundRunner
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// ....
BackgroundRunnerPlugin.registerBackgroundTask()
BackgroundRunnerPlugin.handleApplicationDidFinishLaunching(launchOptions: launchOptions)
// ....
return true
}
为了让后台运行器处理远程通知,添加以下内容:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// ....
BackgroundRunnerPlugin.dispatchEvent(event: "remoteNotification", eventArgs: userInfo) { result in
switch result {
case .success:
completionHandler(.newData)
case .failure:
completionHandler(.failed)
}
}
}
地理位置
Apple 要求在 Info.plist
中为位置信息指定隐私描述:
NSLocationAlwaysUsageDescription
(Privacy - Location Always Usage Description
)NSLocationWhenInUseUsageDescription
(Privacy - Location When In Use Usage Description
)
阅读 iOS 指南 中的 配置 Info.plist
部分,了解更多关于在 Xcode 中设置 iOS 权限的信息。
Android
在 android/app/build.gradle
中插入以下行:
...
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
+ dirs '../../node_modules/@capacitor/background-runner/android/src/main/libs', 'libs'
}
}
...
如果您是从 1.0.5 版本升级现有的 Android 项目,请确保删除 android/src/main/libs
中的 android-js-engine-release.aar
。