我不是 JS/Cordova 开发人员,我是 Android 开发人员。有一次我开发了一个 Cordova 插件,遇到了一些问题并对该主题进行了一些调查。
keepRunning 标志的一般用途是指示当应用暂停(进入后台)时是否应该停止 JS 计时器。回答您的问题:不,它不会创建任何新的服务。现有的设计在这方面很简单。
keepRunning 标志在CordovaActivity.java 中定义如下:
// Keep app running when pause is received. (default = true)
// If true, then the JavaScript and native code continue to run in the background
// when another application (activity) is started.
protected boolean keepRunning = true;
其主要目的是在 Cordova 应用程序暂停时禁用 JS 计时器,CordovaWebView.java:
public void handlePause(boolean keepRunning)
{
LOG.d(TAG, "Handle the pause");
// Send pause event to JavaScript
this.loadUrl("javascript:try{cordova.fireDocumentEvent('pause');}catch(e){console.log('exception firing pause event from native');};");
// Forward to plugins
if (this.pluginManager != null) {
this.pluginManager.onPause(keepRunning);
}
// If app doesn't want to run in background
if (!keepRunning) {
// Pause JavaScript timers (including setInterval)
this.pauseTimers();
}
paused = true;
}
请注意,插件也会通过 PluginManager 得到通知,因此理论上它们可以处理应用暂停事件,在后台停止(或不停止)他们的活动,具体取决于 keepRunning标志。
在我的情况下,当 keepRunning 为 true 时我遇到了问题/错误,但 JS 计时器无论如何都已停止。发生这种情况是因为在CordovaActivity.java 中有与该标志相关的附加功能:
/**
* Launch an activity for which you would like a result when it finished. When this activity exits,
* your onActivityResult() method will be called.
*
* @param command The command object
* @param intent The intent to start
* @param requestCode The request code that is passed to callback to identify the activity
*/
public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
this.activityResultCallback = command;
this.activityResultKeepRunning = this.keepRunning;
// If multitasking turned on, then disable it for activities that return results
if (command != null) {
this.keepRunning = false;
}
// Start activity
super.startActivityForResult(intent, requestCode);
}
当 Cordova 应用启动另一个 Android 活动时,主要的 Cordova 活动(带有 WebView 的屏幕)进入后台并因此暂停。就我而言,它是通过 Google Maps 插件制作的,该插件通过 Cordova 应用程序启动 GM 屏幕。
上面的代码关闭了keepRunning标志,这意味着无论keepRunning是真还是假,当被调用的activity出现时(在CordovaActivity.onPause方法中)JS定时器都会停止!
这看起来像是为某些不清楚(且未记录)的目的而实施的一种技巧,我不知道它的上下文。在我的情况下,它导致了一个错误,我刚刚删除了 startActivityForResult 中的 keepRunning 处理,重新编译了 Cordova,它工作正常。
添加:关于使用 GPS 服务 - 你说得很对,我同意。作为具有相关 (GPS) 经验的 Android 开发人员,我可以说正确的方法(并且可能是唯一可接受的方法)是为此使用服务。据我所知,Cordova 没有为它提供任何功能,所以我认为它应该通过插件制作。我的意思是您可以为 GPS 功能编写原生 Android 代码(作为服务实现)并从 JS 代码访问它。我相信这是 Cordova 中针对此类情况的常见解决方案。