首先默认情况下,ionic3 下对安卓的物理返回键处理,当点击返回键的时候直接退出了程序。
这对于我们的用户体验确实是极其不佳的。
我们通常的做法是:
点击返回键的时候,退回上级路由,当没有路由返回的时候,提示按2次可以退出程序。
怎么做呢,直接看代码吧.
首先我们需要在app.component.ts的platform.ready 方法里处理这一逻辑。
Alert提示框模式
constructor(private platform: Platform, private alertCtrl: AlertController) {
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
// 注册返回键事件监听
platform.registerBackButtonAction(() = >{
// 获取当前激活的nav
let activeNav: NavController = this.appCtrl.getActiveNavs()[0];
if (activeNav.canGoBack()) {
// 退回上一级
activeNav.pop();
} else {
if (this.alert) {
this.alert.dismiss();
this.alert = null;
} else {
this.showAlert();
}
}
});
});
}
// 显示确认框
showAlert() {
this.alert = this.alertCtrl.create({
title: '警告',
message: '确认退出app吗?',
buttons: [{
text: '取消',
role: 'cancel',
handler: () = >{
this.alert = null;
}
},
{
text: '确定',
handler: () = >{
// 退出app
this.platform.exitApp();
}
}]
});
alert.present();
}
Toast 提示框模式
constructor(private platform: Platform, private toastCtrl: ToastController) {
var lastTimeBackPress = 0;
var timePeriodToExit = 2000;
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
// 注册返回键事件监听
platform.registerBackButtonAction(() = >{
// 获取当前激活的nav
let activeNav: NavController = this.appCtrl.getActiveNavs()[0];
if (activeNav.canGoBack()) {
// 退回上一级
activeNav.pop();
} else {
if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
this.platform.exitApp();
} else {
let toast = this.toastCtrl.create({
message: '再按一次退出程序',
duration: 2000,
position: 'bottom'
});
toast.onDidDismiss(() = >{
console.log('Dismissed toast');
});
toast.present();
lastTimeBackPress = new Date().getTime();
}
}
});
});
}
两套代码只是提供了2种不同的展示效果,核心逻辑是一样的。
全部评论