javascript - 应用程序在后台时 setInterval 函数不运行

标签 javascript google-maps timer phonegap-plugins phonegap

我正在开发一个带有 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/

相关文章:

ios - 同时运行两个定时器

java - 计时器和 Action 在java中执行

javascript - 在Select2中向Ajax请求传递参数

javascript - 将带有参数的函数作为参数传递给 jQuery 的回调

javascript - 如何将数组中的重复对象分组

Android谷歌地图,谷歌地点,北纬超过南纬

php - Javascript PHP 更新所有打开的实例,例如 Facebook

android - 地理编码结果而不在 map 上显示它们

java - 在运行时检查位置设置更改

java - 在 JFrame 中创建基本动画