场景一:
在根视图点击安卓返回键,提示,再按一次退出应用,或者 连续点击两次,退出应用。
解决:
新建一个安卓返回键服务,在根页面和登录页使用中使用。如图:
tabs.component.ts:
import { Injectable } from '@angular/core';
import { Platform, ToastController, App, NavController, Tabs ,Keyboard ,Events} from 'ionic-angular';
@Injectable()
export class BackButtonService {
//控制硬件返回按钮是否触发,默认false
backButtonPressed: boolean = false;
//构造函数 依赖注入
constructor(
public platform: Platform,
public appCtrl: App,
public toastCtrl: ToastController,
private keyboard:Keyboard,
private events:Events,
) { }
//注册方法
registerBackButtonAction(tabRef:Tabs):void{
this.platform.registerBackButtonAction(()=>{
if (this.keyboard.isOpen()) {//如果键盘开启则隐藏键盘
this.keyboard.close();
return;
}
const backdrop = document.querySelector('ion-backdrop');
if(backdrop){
//弹窗打开状态,关闭弹窗
this.events.publish("closePop");
return;
}
//获取navController
let activeNav:NavController = this.appCtrl.getActiveNavs()[0];
//如果可以返回上一页,则执行pop,返回上一个页面
if(activeNav.canGoBack()){
activeNav.pop();
}else{
if(tabRef == null || tabRef._selectHistory[tabRef._selectHistory.length -1] === tabRef.getByIndex(0).id){
//执行退出
this.showExit();
}else {
//选择首页第一个的标签
tabRef.select(0);
}
}
})
}
//退出应用的方法
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,如果是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();
}