Ionic 3+ solving the hardware back button, avoiding to close the app
Imagem da internet, edição: Everton Costa

Ionic 3+ solving the hardware back button, avoiding to close the app

Who doesn't? Believed in its own code at the point of dying for it... Welcome, I am a mobile developer that always is facing challenges and looking for solutions.

The problem I wanted to solve

Think about, so you finished your project after months, or at least long hours working on that. And finally you show it up to the costumer. You prepared the flow, menu, tabs, everything to navigate in the app, and so on. But surprise! The first thing the user does is tap the hardware back button, "zzzumpt" your app desapear of the user eyes and some times the app crashes...

The hardware (headache) back button

Android devices have a built in "back" button. By default, when user presses the Android hardware back button, the navigation has to pop a screen or exit the app if there are no screens to pop. If you are using Ionic to develop, I might suggest you to take so much care about this.

To start we will use the Ionic Platform service. It can be used to get information about your current device through the platforms method, including whether the app is being viewed from a tablet, if it's on a mobile device or browser, and the exact platform (iOS, Android, etc). Also we will use the registerBackButtonAction() function associated to Platform method. And that's it, simple like that!

The process

In the app folder open up your app.component.ts file to start implementing the function:

platform.registerBackButtonAction(() => { 

});

This function accepts also one more parameter called priority, but we will not cover this part in this article, we can talk more about it a little bit if you ask me later.

Considering that we are using lazy loading approach. Firstly let's import the App component and declare it in the constructor, as we will use it to manage and acquire the current view name.

import { App } from 'ionic-angular';

constructor(public app: App) {

}

Your final code will be like that:

import { Nav, Platform, AlertController } from 'ionic-angular';

import { SplashScreen } from '@ionic-native/splash-screen';

import { Component, ViewChild } from '@angular/core';

import { StatusBar } from '@ionic-native/status-bar';

import { App } from 'ionic-angular';


@Component({

 templateUrl: 'app.html'

})


export class MyApp {


 @ViewChild(Nav) nav: Nav;

 rootPage: any = 'HomePage';

 pages: Array<{title: string, component: any}>;


 constructor(
  private splashScreen: SplashScreen,
  public alertCtrl: AlertController,
  private statusBar: StatusBar,
  private platform: Platform, 
  private app: App,
 ){

  this.initializeApp();

  // used for an example of ngFor and navigation

  this.pages = [

   { title: 'Home', component: 'HomePage' },

   { title: 'Lista', component: 'ListPage' },

   { title: 'Sobre', component: 'SobrePage' },

   { title: 'Vazia', component: 'VaziaPage' },

  ];

 }


 initializeApp() {

  this.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.

   this.statusBar.styleDefault();

   this.splashScreen.hide();

  });

  this.platform.registerBackButtonAction(() => {

   // Catches the active view

   let nav = this.app.getActiveNavs()[0];

   let activeView = nav.getActive();         

   // Checks if can go back before show up the alert

   if(activeView.name === 'HomePage') {

     if (nav.canGoBack()){

       nav.pop();

     } else {

       const alert = this.alertCtrl.create({

         title: 'Fechar o App',

         message: 'Você tem certeza?',

         buttons: [{

           text: 'Cancelar',

           role: 'cancel',

           handler: () => {

            this.nav.setRoot('HomePage');

            console.log('** Saída do App Cancelada! **');

           }

         },{

           text: 'Fechar o App',

           handler: () => {

            this.logout();

            this.platform.exitApp();

           }

         }]

       });

       alert.present();

     }

   }

 });

 }

 openPage(page) {

   // Reset the content nav to have just this page

   // we wouldn't want the back button to show in this scenario

   this.nav.setRoot(page.component);

 }  

 logout() {

   this.nav.setRoot('LoginPage');

 }

}

Conclusion

It was not difficult to solve this kind of situation using my expertise and the Ionic Framework documentation page, there are a lot of docs about it and the Forum to claim for help. Some times I am the one who helps others, and some times I am the one who ask for support also.

This tips is to grantee that your apps will not crash or at least not close at users faces. So I hope it cam be useful to increase the quality of your code and contribute to a better user experience.

Pay attention and always take care about UX (user experience) in your apps and development projects. It can be a rouge difference between a simple good one app and a nice one with strong usability experience.

Feel free to keep in touch, or call me to a live. You can find me and add my profile on Github, Codementor and follow me on Twitter.

Hope to see you soon!

To view or add a comment, sign in

More articles by ☕ Everton Costa

Others also viewed

Explore content categories