在Ionic2项目结构解析中,我们知道在 src/app/app.component.ts 初始化项目,因此我们可以在这里监听Android返回按键,实现双击退出应用。
Ionic2 Platform中提供了监听返回按键的API registerBackButtonAction(callback, priority),
参数 | 类型 | 描述 |
---|---|---|
callback | Function | 返回键触发时执行的方法 |
priority | number | 优先级,优先级高的会先执行,默认为0 |
注册返回按键事件
修改src/app/app.component.ts如下:
import { Component, ViewChild } from '@angular/core';
import { Platform, ToastController, Nav } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { TabsPage } from '../pages/tabs/tabs';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage = TabsPage;
backButtonPressed: boolean = false; //用于判断返回键是否触发
@ViewChild(Nav) nav: Nav;
constructor(public platform: Platform, public toastCtrl: ToastController) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
StatusBar.styleDefault();
Splashscreen.hide();
//注册返回按键事件
this.platform.registerBackButtonAction((): any => {
let activeVC = this.nav.getActive();
let page = activeVC.instance;
if (!(page instanceof TabsPage)) {
if (!this.nav.canGoBack()) {
//当前页面为tabs,退出APP
return this.showExit();
}
//当前页面为tabs的子页面,正常返回
return this.nav.pop();
}
let tabs = page.tabs;
let activeNav = tabs.getSelected();
if (!activeNav.canGoBack()) {
//当前页面为tab栏,退出APP
return this.showExit();
}
//当前页面为tab栏的子页面,正常返回
return activeNav.pop();
}, 101);
});
}
//双击退出提示框,这里使用Ionic2的ToastController
showExit() {
if (this.backButtonPressed) this.platform.exitApp(); //当触发标志为true时,即2秒内双击返回按键则退出APP
else {
let toast = this.toastCtrl.create({
message: '再按一次退出应用',
duration: 2000,
position: 'bottom'
});
toast.present();
this.backButtonPressed = true;
//2秒内没有再次点击返回则将触发标志标记为false
setTimeout(() => {
this.backButtonPressed = false;
}, 2000)
}
}
}
修改 src/pages/tabs/tabs.html
<ion-tabs #mainTabs>
<ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
<ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion-tab>
<ion-tab [root]="tab3Root" tabTitle="Contact" tabIcon="contacts"></ion-tab>
</ion-tabs>
修改 src/pages/tabs/tabs.ts
import { Component,ViewChild } from '@angular/core';
import { Tabs } from 'ionic-angular';
import { HomePage } from '../home/home';
import { AboutPage } from '../about/about';
import { ContactPage } from '../contact/contact';
@Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
@ViewChild('mainTabs') tabs:Tabs;
//根据html中的'#mainTabs'获取Tabs实例
tab1Root: any = HomePage;
tab2Root: any = AboutPage;
tab3Root: any = ContactPage;
constructor() {
}
}
转自https://dpary.github.io/2016/12/19/
方案2(若前面方法不可用使用该方法)
import {App} from ‘ionic-angular’
this.platform.registerBackButtonAction(() => {
const overlay = this.app._appRoot._overlayPortal.getActive();
const nav = this.app.getActiveNav();
if (overlay && overlay.dismiss) {
overlay.dismiss();
} else if (nav.canGoBack()) {
nav.pop();
} else {
this.platform.exitApp();
}
}, 101)