paint-brush
Handling Android Back Button in Ionicby@Ourarash
17,162 reads
17,162 reads

Handling Android Back Button in Ionic

by Ari SaifMarch 7th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<strong>Summary</strong>: This is a comprehensive method for handling Android back button in Ionic 2 and Ionic 3. The back button will behave like in Instagram: it will close the side menu or any pushed pages, and it will also circle between most recently used tabs.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Handling Android Back Button in Ionic
Ari Saif HackerNoon profile picture

Summary: This is a comprehensive method for handling Android back button in Ionic 2 and Ionic 3. The back button will behave like in Instagram: it will close the side menu or any pushed pages, and it will also circle between most recently used tabs.

Note: If you are an advanced user and just want to see the result, you can clone the demo project from my github.

Handling Android Back Button in Ionic

Introduction

Handling Android Back button have been addressed in several places, such as here. But I didn’t find any of them to be comprehensive and complete. I needed a method that does the following:

  • Closes the side menu if it was open
  • Closes any pages that might have been pushed on any of the tab pages’ nav controller
  • If the menu was closed, and there was no pushed page, it should take the user back to the previous recently used tab.
  • If there was no previous recently used tab, an alert box should ask the user if they want to exit.

In this article, I quickly explain how to perform the above.

Summary of the Plan

We will perform the following:

  • We create a new service called backbuttonService, so that each tab page can register its navCtrl into this service’s stack. The stack will be used to circle around most recently used tabs
  • We will create a function to hook into back button in app.component.ts file.
  • In the hook function, we check for menu, any pushed pages on the navCtrl’s in backbuttonService’s stack.
  • We also write a function to switch between tabs programmatically.

Getting Started

You can create a new ionic 3 project by running the following in the command line, accept the default options and cd into the backbutton folder:

ionic start backbutton sidemenu

Create New Tab Pages

Now, add three tab pages to this project:



ionic generate page page1 --no-moduleionic generate page page2 --no-moduleionic generate page page3 --no-module

You will need to add these pages to app.module.ts. Add the following to the beginning of the file:



import { Page1Page } from '../pages/page1/page1';import { Page2Page } from '../pages/page2/page2';import { Page3Page } from '../pages/page3/page3';

Also, add them to declarations and entryComponents in the same file:








declarations: [MyApp,HomePage,ListPage,Page1Page, // Add this line!Page2Page, // Add this line!Page3Page, // Add this line!],

...








entryComponents: [MyApp,HomePage,ListPage,Page1Page, // Add this line!Page2Page, // Add this line!Page3Page, // Add this line!],

Create a New Service: BackbuttonService

Create a new folder and file under src:

src/services/backbutton.service.ts

Note: Rather than copying the complete file here, you can get it from my github.

This file has two simple functions for push and pop of tab pages so that we can track the most recently used tab page.

You also need to register the service in app.module.ts:







import { BackbuttonService } from "../services/backbutton.service";...providers: [StatusBar,SplashScreen,BackbuttonService, // Add this line!]

Create a Global Variable for Tabs:

Create a new file called app.config.ts. You can put it anywhere. I chose to put it under src/app. It contains the following:







//Enum variable for tabexport var EN_TAB_PAGES = {EN_TP_HOME: 0,EN_TP_PLANET:1,EN_TP_STAR: 2,EN_TP_LENGTH: 3,}


//A global variableexport var Globals = {


//Nav ctrl of each tab pagenavCtrls : new Array(EN_TAB_PAGES.EN_TP_LENGTH),



tabIndex:0, //Index of the current tabtabs: <any>{}, //Hook to the tab object}

Adding Hook Function to app.component.ts

We add three functions to this file:

  • registerBackButton: hooks to Cordova’s function for handing Android back button. It first checks if the side menu is open, and if so, closes the menu.
  • showAlert: Shows an alert asking the user if they are sure to exit
  • switchTab: Switches between tabs programmatically

Since the changes are long, I don’t copy them here, but you can see the detailed changes on my github.

Pushing Each Tab Page into the Stack

Each time we open a new tab page, we should push it into the stack. If it already exists in the stack, we remove it and add it again. This will create the Instagram effect where we circle around recently used tabs but we won’t go through the same tab twice. In order to do so, we inject the backbuttonService in each tab page and use it.

In each tab page add the following:


import { BackbuttonService } from '../../services/backbutton.service';import { EN_TAB_PAGES } from "../../app/app.config";

...




//Inject the serviceconstructor(public navCtrl: NavController,public navParams: NavParams,private backbuttonService: BackbuttonService,

) {}

...




ionViewWillEnter() {this.backbuttonService.pushPage(EN_TAB_PAGES.EN_TP_HOME,this.navCtrl);}

In the above code, note that for each tab page, you should use its own EN_TAB_PAGES value.

That’s it! If you liked this tutorial, please share and clap. I would really appreciate it!

Also, for production-level Ionic apps that handle Android back button correctly, please check my following apps: