我在移动Ionic应用程序中有一个视图,它定期刷新后台数据。我希望在以下时间停止发生:
现在我通过以下方式完成这些:
$scope.$on('$ionicView.beforeLeave', pauseUpdates);
$scope.$on('$ionicView.enter', restartUpdates);
document.addEventListener("pause", pauseUpdates, false);
document.addEventListener("resume", restartUpdates, false);
然而,这引入了一个边缘情况,用户进入我的视图,然后返回到另一个视图,将应用程序放在后台,然后切换回它(我重新启动更新,当我不应该)。
在我制作某种isNotCurrentView变量进行跟踪之前 - 我是否完全以错误的方式进行此操作?是否有一些更简洁的方式来跟踪我的状态?我总是暗自觉得使用addEventListener是一种不太强烈的方式来解决这个问题......
答案 0 :(得分:2)
After a bit of digging around I've found a more elegant solution to this. As per https://forum.ionicframework.com/t/best-way-to-intercept-events-like-cordova-resume-and-pause-in-ionic/4720/5, a good way to deal with these is to add document-level handlers which fire root-scope broadcasts:
.run(function ($ionicPlatform, $rootScope) {
$ionicPlatform.ready(function () {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
console.log('run() -> onDeviceReady');
document.addEventListener("pause", function (event) {
console.log('run() -> cordovaPauseEvent');
$rootScope.$broadcast('cordovaPauseEvent');
});
document.addEventListener("resume", function (event) {
console.log('run() -> cordovaResumeEvent');
$rootScope.$broadcast('cordovaResumeEvent');
});
}
}
Inside your actual controller, you can then handle these like so:
$scope.$on('cordovaPauseEvent', pauseTotalsUpdates);
When the view using your controller is no longer active, Ionic's view caching will keep the controller in memory but will de-activate its $scope. This means that your controller won't run pause/resume events unless it's the active controller. Remember to attach the $on event to $scope and not $rootScope, as that is not detached when your controller goes out of view.
答案 1 :(得分:0)
您是否知道可以依赖https://github.com/angular-ui/ui-router/wiki中的 $ stateChangeStart 事件?
因此,您可以在控制器中使用此处理程序保留当前状态/视图:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
...
});
此外,您可以使用cordova-plugin-background-mode来跟踪"激活bkg模式等事件" (参见onactivate)或"从bkg模式恢复" (见ondeactivate)。