Cordova检查关闭应用程序事件并保存日期/时间

Cordova check close app event and save date/time

本文关键字:保存 日期 时间 事件 检查 应用程序 Cordova      更新时间:2023-09-26

当我的用户暂停他们的应用程序时,我会将日期保存在window.localStorage对象中,这样当应用程序恢复时,我可以向服务器发送请求,并查看是否有新消息给他们。这是有效的,但当他们关闭应用程序并重新启动时,我需要再次设置日期,这样我就无法检查在他们关闭和重新启动之间是否有消息,因为这与暂停和恢复不同。这里有一个代码示例来展示我的意思。

这是应用程序启动的时候:

$ionicPlatform.ready(function() {
    var now = new Date();
    var year =   now.getFullYear();
    var month =   now.getMonth() + 1;
    var days =   now.getDate();
    var hours =   now.getHours();
    var minutes =   now.getMinutes();
    var seconds =   now.getSeconds();
    var now = year + '-' + month + '-' + days + ' ' + hours + ':' + minutes + ':' + seconds; 
    window.localStorage.setItem('lastActive',now);
});

这些是暂停/恢复功能

document.addEventListener("resume", onResume, false);
document.addEventListener("pause", onPause, false);

function onResume() {
    if(window.localStorage.getItem('lastActive')){
        var lastActive = window.localStorage.getItem('lastActive');
        console.log('last seen on: '+lastActive);
        $http({method: 'get', url: '***/api.php/inbox/'+window.localStorage.getItem('auth')+'/'+lastActive}).
        success(function(data, status, headers, config) {
            if(data.new < 1){
                $scope.newcount = data.new
            }else{
                $scope.newcount = data.new
            }
        }).error(function(data, status, headers, config) {
            $cordovaToast.showShortTop("are you connected to the internet?").then(function(success) {
            }, function (error) {
                alert("are you connected to the internet?");
            });
        }); 
    }else{
        console.log('lastst online: unkown');
    }
}
function onPause() {
    var now = new Date();
    var year =   now.getFullYear();
    var month =   now.getMonth() + 1;
    var days =   now.getDate();
    var hours =   now.getHours() + 1;
    var minutes =   now.getMinutes();
    var seconds =   now.getSeconds();
    var now = year + '-' + month + '-' + days + ' ' + hours + ':' + minutes + ':' + seconds; 
    window.localStorage.setItem('lastActive',now);
    window.localStorage.setItem('lastActivejs',new Date());
}

现在,当应用程序get关闭时,ionicplatform.ready函数get再次启动,以设置最后一个活动日期,因为我无法在关闭时设置一个。我相信其他人必须处理这个问题,并想知道你是如何处理的。

这可能对您来说并不理想,但我通过将当前时间设置为每分钟一次的localStorage来解决这一问题,然后当我的应用程序打开时,我的ready()函数所做的第一件事就是检查localStorage值和Date.now()之间的差异。这听起来像是一个性能杀手,但它在我的应用程序中运行良好–最好在依赖它之前在您的应用程序进行测试。我这样做:

function ticker() {
  var n=Date.now();
  if (n%60000<20) {
    localStorage.setItem("last_tick",n);
  }
  requestAnimationFrame(ticker);
}

呼叫ticker()以启动它。requestAnimationFrame()允许浏览器进行优化。然而,如果你的应用程序进入后台,WebKit引擎会降低调用ticker()的频率,并可能完全停止它,所以你可能会发现你需要使用setInterval(),这可能会带来它自己的性能问题(尽管我仍然认为这会很好)。你的问题是其他人是如何绕过这一点的,这对我来说是有效的。