由于是全局事件,所以直接在app.component.ts中写
头文件中添加
import { Platform, ToastController} from 'ionic-angular';
import { SettingsProvider } from '../providers/settings/settings';
然后进行定义
backButtonPressed: boolean = false; //用于判断返回键是否触发
@ViewChild('myNav') nav:Nav;
前端改为:
<ion-nav [root]="rootPage" [class]="selectedTheme" #myNav [root]="rootPage"></ion-nav>
构造函数
constructor(platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
public platform1: Platform,
public ionicApp: IonicApp,
public settings:SettingsProvider,
public toastCtrl: ToastController) {
platform.ready().then(() => {
statusBar.styleDefault();
splashScreen.hide();
this.registerBackButtonAction();//注册返回按键事件
});
}
下面定义的两个函数,分别是事件和提示框
registerBackButtonAction() {
this.platform1.registerBackButtonAction(() => {
let activePortal = this.ionicApp._modalPortal.getActive();
if (activePortal) {
activePortal.dismiss().catch(() => {});
activePortal.onDidDismiss(() => {});
return;
}
let activeVC = this.nav.getActive();
let tabs = activeVC.instance.tabs;
let activeNav = tabs.getSelected();
return activeNav.canGoBack() ? activeNav.pop() : this.showExit()
}, 1);
}
//双击退出提示框
showExit() {
if (this.settings.backButtonPressed) { //当触发标志为true时,即2秒内双击返回按键则退出APP
this.platform1.exitApp();
} else {
this.toastCtrl.create({
message: '再按一次退出应用',
duration: 2000,
position: 'top'
}).present();
this.settings.backButtonPressed = true;
setTimeout(() => this.settings.backButtonPressed = false, 2000);//2秒内没有再次点击返回则将触发标志标记为false
}
}
想设立关闭键
setting.html界面
<button ion-item (click)= "Appdimiss()">
<ion-icon name="close-circle" item-start color="dark"></ion-icon>
<ion-label>关闭</ion-label>
</button>
页面的setting.ts文件
导入
import { SettingsProvider } from '../../providers/settings/settings';
import { Platform, IonicPage, NavController, NavParams, ViewController,IonicApp,ToastController} from 'ionic-angular';
构造
public settings:SettingsProvider,
public platform1: Platform,
public toastCtrl: ToastController,
函数
Appdimiss(){
if (this.settings.backButtonPressed) { //当触发标志为true时,即2秒内双击返回按键则退出APP
this.platform1.exitApp();
} else {
this.toastCtrl.create({
message: '再按一次退出应用',
duration: 2000,
position: 'top'
}).present();
this.settings.backButtonPressed = true;
setTimeout(() => this.settings.backButtonPressed = false, 2000);//2秒内没有再次点击返回则将触发标志标记为false
}
}
providers里面的setting.ts,目的是设置为全局变量,使按键和返回键行使统一效果
public backButtonPressed: boolean = false;
这样无论是按我们设置的按键还是返回键,在两秒内按另一个都可以结束程序。
效果图: