本篇文章給大家分享的是有關(guān)android硬件中的返回按鈕如何利用ionic2進(jìn)行處理,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
問題
注冊安卓硬件返回按鈕事件是必須的,因為用戶不小心點擊了返回按鈕就退出app體驗很不好,所以有幾種方法:
1.實現(xiàn)按返回鍵最小化應(yīng)用(最小化應(yīng)用需要裝cordova-plugin-appminimize插件,使用window['AppMinimize'].minimize();)。
2.要么請求用戶確認(rèn)(添加一個Confirmation Alerts)。
3.按一下提示,按兩下退出(加一個方法用toast提醒)。
這里用第三種展示。
解決
在app.html中,添加#myNav,在app.component.ts文件通過@ViewChild('myNav')獲?。?/p>
在app.component.ts中:
import {Component, ViewChild} from '@angular/core'; import {Platform, ToastController, Nav, IonicApp} 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; //用于判斷返回鍵是否觸發(fā) @ViewChild('myNav') nav: Nav; constructor(public ionicApp: IonicApp, public platform: Platform, public toastCtrl: ToastController) { platform.ready().then(() => { StatusBar.styleDefault(); Splashscreen.hide(); this.registerBackButtonAction();//注冊返回按鍵事件 }); } registerBackButtonAction() { this.platform.registerBackButtonAction(() => { //如果想點擊返回按鈕隱藏toast或loading或Overlay就把下面加上 // this.ionicApp._toastPortal.getActive() || this.ionicApp._loadingPortal.getActive() || this.ionicApp._overlayPortal.getActive() 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();//另外兩種方法在這里將this.showExit()改為其他兩種的方法的邏輯就好。 }, 1); } //雙擊退出提示框 showExit() { if (this.backButtonPressed) { //當(dāng)觸發(fā)標(biāo)志為true時,即2秒內(nèi)雙擊返回按鍵則退出APP this.platform.exitApp(); } else { this.toastCtrl.create({ message: '再按一次退出應(yīng)用', duration: 2000, position: 'top' }).present(); this.backButtonPressed = true; setTimeout(() => this.backButtonPressed = false, 2000);//2秒內(nèi)沒有再次點擊返回則將觸發(fā)標(biāo)志標(biāo)記為false } } }