当我的用户暂停他们的应用时,我将日期保存在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());
}
现在当应用程序关闭时,ionicplatform.ready函数再次被触发以设置最后一个活动日期,因为我无法在关闭时设置一个。我确定其他人不得不处理这个问题,并想知道你是如何处理它的。
答案 0 :(得分:1)
这对你来说可能并不理想,但我通过将当前时间设置为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()
,这可能会带来它自身的性能问题(虽然我仍然认为它会没事)。你的问题是其他人是如何解决这个问题的,这对我有用。