Ionic 实现双击返回键退出功能

时间:2022-09-18 10:06:41

  app.js 代码如下:

 
var myApp = angular.module('myApp',['ionic','ngCordova']);


myApp.controller('MyController', function($scope) {
var count=0;
$scope.lstorage="abcdd";
$scope.sayHello = function() {
console.log("------MyController.sayHello()");
alert("hello!");
}
});

myApp.run(function ($ionicPlatform, $rootScope, $location, $timeout, $ionicHistory, $cordovaToast) {
$ionicPlatform.ready(function ($rootScope) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
console.log("-----------------------1");
});
//双击退出
$ionicPlatform.registerBackButtonAction(function (e) {
//判断处于哪个页面时双击退出
if ($location.path() == '/index.html') {
if ($rootScope.backButtonPressedOnceToExit) {
ionic.Platform.exitApp();
} else {
$rootScope.backButtonPressedOnceToExit = true;
$cordovaToast.showShortTop('再按一次退出系统');
setTimeout(function () {
$rootScope.backButtonPressedOnceToExit = false;
}, 2000);
}
console.log("-----------------------2");
}
else if ($ionicHistory.backView()) {
console.log("-----------------------3");
$ionicHistory.goBack();

} else {
$rootScope.backButtonPressedOnceToExit = true;
$cordovaToast.showShortTop('再按一次退出系统');
setTimeout(function () {
$rootScope.backButtonPressedOnceToExit = false;
}, 2000);
console.log("-----------------------4");
}
e.preventDefault();
return false;
}, 101);
});


以上脚本用了

cordova plugin add https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin.git
插件,自行安装一下