场景一:
在根视图点击安卓返回键,提示,再按一次退出应用,或者 连续点击两次,退出应用。
解决:
新建一个安卓返回键服务,在根页面和登录页使用中使用。如图:
tabs.component.ts:
import { Component } from '@angular/core';
import { Platform, ToastController, Keyboard, IonicApp, NavController, App } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = 'TabsPage';
//控制硬件返回按钮是否触发,默认false
backButtonPressed: boolean = false;
constructor(
public platform: Platform,
public statusBar: StatusBar,
public splashScreen: SplashScreen,
public toastCtrl: ToastController,
public keyboard:Keyboard,
public ionicApp: IonicApp,
public appCtrl: App,
) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleLightContent();
splashScreen.hide();
this.registerBackButtonAction(); //注册返回按键事件
});
}
//注册方法
registerBackButtonAction(): void {
//registerBackButtonAction是系统自带的方法
this.platform.registerBackButtonAction(() => {
if (this.keyboard.isOpen()) return this.keyboard.close();
let activePortal = this.ionicApp._modalPortal.getActive()
|| this.ionicApp._toastPortal.getActive()
|| this.ionicApp._loadingPortal.getActive()
|| this.ionicApp._overlayPortal.getActive()
if (activePortal) return activePortal.dismiss();
let activeNav:NavController = this.appCtrl.getActiveNavs()[0];
return activeNav.canGoBack() ? activeNav.pop() : this.showExit();
});
}
//退出应用方法
private showExit(): void {
//如果为true,退出
if (this.backButtonPressed) {
this.platform.exitApp();
} else {
//第一次按,弹出Toast
this.toastCtrl.create({
message: '再按一次退出应用',
duration: 2000,
position: 'top'
}).present();
//标记为true
this.backButtonPressed = true;
//两秒后标记为false,如果退出的话,就不会执行了
setTimeout(() => this.backButtonPressed = false, 2000);
}
}
}
场景二:
在某个页面之后点击按钮,返回某个页面(并不是上一个页面)时,使用安卓返回键,会返回上一页,与按钮不符。
解决:
1.引入navbar 组件
2.注册安卓返回键事件
图上,是直接返回跟页面,如若不是返回根页面,则获取要返回页面的index,根据index跳转到该页面,如图:
看屏蔽部分
场景三:
当有弹窗时,点击返回键(不管是安卓返回键还是页面上的返回按钮),应先关闭弹窗,再次点击之后才返回页面。
安卓返回键:如最上面的双击退出中有涉及到。
页面返回按钮:
因为navbar组件自带返回,点一下就返回了,因此,我选择自己写了头部显示。然后在按钮上加入返回事件即可
backLastPage(){
let activePortal = this.ionicApp._modalPortal.getActive() ||this.ionicApp._overlayPortal.getActive();
console.log(activePortal);
if (activePortal) {
//其他的关闭
activePortal.dismiss().catch(() => {});
activePortal.onDidDismiss(() => {});
return;
}
this.navCtrl.pop();
}