【发布时间】:2019-03-11 06:11:48
【问题描述】:
(经过编辑以提供更新的信息)
我有一个 nativescript 应用程序,如果手机进入后台模式或被锁定,我想继续执行各种任务。
专注于 iOS,使用 Nativescript Angular。我对在 Nativescript 中使用 obj C 代码也很陌生。
举个简单的例子,假设我想在用户点击按钮后每 5 秒打印一次到控制台,所以我的组件 ts 文件中有以下代码:
coolComponent.ts:
@Component({...})
Export class coolComponent {
...
whenButtonClicked(){
setInterval(function(){
console.log('button has been clicked. show every 5 seconds!');
}, 5000);
}
无需进一步的代码,当用户点击按钮时,它将每 5 秒打印到控制台,但当应用程序处于后台或手机锁定时停止。即使应用处于后台或锁定状态,如何让函数继续执行?
看到不同的来源,如 here (NS docs on background execution) 和 here (docs on app delegate) ,第一步似乎是创建一个自定义应用程序委托,让它工作,然后在 info.plist 中识别后台任务。
我已经得到了一般的功能,像这样:
app/custom-app-delegate.ts:
import { ios, run as applicationRun } from "tns-core-modules/application";
export class CustomAppDelegate extends UIResponder implements
UIApplicationDelegate {
public static ObjCProtocols = [UIApplicationDelegate];
public applicationDidEnterBackground(application: UIApplication) {
console.log('in background mode!')
}
}
main.ts:
import { platformNativeScriptDynamic } from "nativescript-angular/platform";
import { AppModule } from "./app.module";
import * as application from "tns-core-modules/application";
import { CustomAppDelegate } from "./custom-app-delegate";
application.ios.delegate = CustomAppDelegate;
platformNativeScriptDynamic().bootstrapModule(AppModule);
app/app.module.ts:
import { CustomAppDelegate } from "./custom-app-delegate";
app/App_Resources/iOS/info.plist:
...
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
</array>
编辑:创建reference.d.ts:
/// <reference path="./node_modules/tns-platform-declarations/ios.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/android.d.ts" />
编辑:仅供参考,为了让 custom-app-delegate 工作,我还必须使用以下命令下载“tns-platform-declerations”:
$ npm i tns-platform-declarations --save-dev
有了这个,应用程序正确读取“在后台模式!”当应用程序进入后台时。所以 custom-app-delegate 是功能性的。
但是,在线示例假定 custom-app-delegate 中的代码独立于应用程序的其余部分,因此它们假定当应用程序进入后台模式时有新任务要做。
这里不是这样。我有一个从coolComponent 函数执行的任务,当应用程序进入后台或被锁定时,我希望它继续。
这可能需要coolComponent.ts 与custom-app-delegate 通信,但我不知道该怎么做。
只是在两个文件中重复代码——让 setInterval 函数出现在 coolComponent.ts 和 custom-app-delegate 中——是行不通的,因为这不会导致 custom-app-delegate 在同一个文件上继续用户点击按钮后在coolComponent.ts 中开始的计时。
那么我怎样才能让代码在coolComponent.ts中启动并在应用程序处于后台模式后继续?
【问题讨论】:
-
您好,我也有同样的问题,您找到解决方案了吗?如果你这样做了,那么你能告诉我如何处理它。
-
我不知道如何使用应用委托执行后台任务。相反,我所做的是尝试找到其他解决方案(其他人已经弄清楚了)。例如,我使用 nativescript 本地通知插件来安排并显示用户通知,即使应用程序在后台。
标签: ios angular nativescript