我正在开发一个带有 phonegap 的简单应用程序,它每 30 秒通过 ajax 调用将用户当前坐标发送到我的数据库。它运行良好
$(document).ready(function() {
setInterval(function() {
SetLocationUpdates();
}, 30000);
});
如果应用程序在前台,则没有问题,一切正常,但如果我使用此代码打开谷歌地图应用程序
<div><a href="geo:41.897096,27.036545">Open maps app</div>
我的应用程序进入后台(我的应用程序和谷歌地图应用程序分开工作。两个应用程序同时工作)并且不再执行间隔功能。
是否可以使用 phonegap 在后台执行 javascript 代码(计时器函数)?
编辑:
我使用 cordova-plugin-background-mode( https://github.com/katzer/cordova-plugin-background-mode ) 但它仍然不起作用。警报给出 false。这有什么问题吗?
document.addEventListener('deviceready', function () {
cordova.plugins.backgroundMode.enable();
alert(cordova.plugins.backgroundMode.isActive());
}, false);
最佳答案
我一直在寻找同一问题的解决方案,我想我只是找到了一个,虽然我还没有能够完全尝试这个,但我想无论如何我都会在这里发布答案,所以你可以也试试吧。
一个解决方案是在 native 代码中设置计时器,而不是 JavaScript,并且似乎有一个 Cordova 插件用于此目的:
https://github.com/dukhanov/cordova-background-timer
安装Cordova插件后,你可以像这样使用它(从文档中粘贴):
var eventCallback = function() {
// timer event fired
}
var successCallback = function() {
// timer plugin configured successfully
}
var errorCallback = function(e) {
// an error occurred
}
var settings = {
timerInterval: 60000, // interval between ticks of the timer in milliseconds (Default: 60000)
startOnBoot: true, // enable this to start timer after the device was restarted (Default: false)
stopOnTerminate: true, // set to true to force stop timer in case the app is terminated (User closed the app and etc.) (Default: true)
hours: 12, // delay timer to start at certain time (Default: -1)
minutes: 0, // delay timer to start at certain time (Default: -1)
}
window.BackgroundTimer.onTimerEvent(eventCallback); // subscribe on timer event
// timer will start at 12:00
window.BackgroundTimer.start(successCallback, errorCallback, settings);
关于javascript - 应用程序在后台时 setInterval 函数不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46179744/