How To Exit App On Back Press | Ionic 4

Beginners in Ionic 4 Android development will encounter a problem wherein the app does not exit on back press from the root component. In this article, we show you how to achieve the same from any component in your Ionic 4 app.

1. Importing The Platform Class

Let’s approach the problem logically. We need to react to the user’s touch of the back button. Therefore, we are going to need a notification whenever that happens.

This is achieved by using the Platform class to subscribe to the BackButtonEmitter. We do this by first importing this class from ‘@ionic/angular’ followed by the creation of an object of Platform in the constructor of the component.

Import Platform class at the top of your component.

import { Platform } from '@ionic/angular';

Create an object of Platform class.

constructor (private platform: Platform) { }

The Platform class contains a property called ‘backButton’ which we can subscribe to, in order to get notifications when the user taps on the back button.

2. Importing Necessary Interfaces

Firstly, it is important to subscribe to the back press event right after the component has finished initializing. The ngAfterViewInit() method is a callback method that is invoked immediately after Angular has completed initialization of a component’s view. It is invoked only once when the view is instantiated.

Secondly, since we are subscribing to an event, hence we also need to unsubscribe from it in order to clean up after the user has left the component. This is done in order to prevent memory leaks.

Learn More: Angular – Lifecycle Hooks

Import OnInit, OnDestroy and AfterViewInit

import { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';

Please Note: The Component and OnInit interfaces are imported by default when you create a new Page in Ionic 4.

Next, we will need to make the component class implement these interfaces.

export class HomePage implements OnInit, OnDestroy, AfterViewInit {
  constructor (private platform: Platform) { }

  ngOnInit() { }
  ngAfterViewInit() { }
  ngOnDestroy() { }
}

With this done, we are finally ready to subscribe to the back-press event.

3. Subscribing To The Back Press Event

In the ngAfterViewInit() subscribe to the Ionic BackButtonEmitter via the Platform.backButton property.

Learn more about Observables in Angular

import { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';
import { Platform } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit, OnDestroy, AfterViewInit {
  constructor (private platform: Platform) { }

  ngOnInit() { }
  ngAfterViewInit() {
    this.platform.backButton.subscribe();
  }
  ngOnDestroy() { }
}

4. Programmatically Exiting The App

Now, we come to the stage where we instruct the app to exit on back press. We use the Navigator interface to call the exitApp() method and exit the app.

import { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';
import { Platform } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit, OnDestroy, AfterViewInit {
  backButtonSubscription; 
  // for storing the returned subscription

  constructor (private platform: Platform) { }

  ngOnInit() { }
  ngAfterViewInit() {
    this.backButtonSubscription = this.platform.backButton.subscribe(() => {
      navigator['app'].exitApp();
    });
  }
  ngOnDestroy() { }
}

Please Note: The subscribe() method will return the subscription, which is in turn stored in a class property backButtonSubscription that we declare.

5. Unsubscribing From The Back Press Event

As I mentioned earlier, we need to make sure we unsubscribe our subscriptions in order to ensure that our app does not create memory leaks. The unsubscription should be performed right before the component is being destroyed, or in other words, reached the end of its lifecycle.

import { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';
import { Platform } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit, OnDestroy, AfterViewInit {
  backButtonSubscription; 
  // for storing the returned subscription

  constructor (private platform: Platform) { }

  ngOnInit() { }
  ngAfterViewInit() {
    this.backButtonSubscription = this.platform.backButton.subscribe(() => {
      navigator['app'].exitApp();
    });
  }

  ngOnDestroy() {
    this.backButtonSubscription.unsubscribe();
  }
}

That’s all folks! If you have queries or doubts, do not hesitate to start a discussion below.