Android hardware back button in ionic

Thanks for the example. Just what I was searching for. The app-exit on back was driving me crazy.

Yes me too. You are welcome!

Canā€™t quite see why you would want to register this more than once?
In my app, instead of calling exitApp() in the else clause, I display an alert to give the user the option to either go to the return page or exit the appā€¦

My solution is good for me :). If you have another then post it to world!

Your solution is great. iā€™m merely pointing to the fact that, once you register the BackButtonAction to the platform, it will work for all pages (my comment was in reply to the thread that asked if this should be used on all pages). Iā€™m not proposing an alternative solution - so no need to post anything ā€˜to the worldā€™ ā€¦

thanks @NyaO your code works for me, this is my code, only I added the actionSheet to confirm, but now I need detect if the actionSheet is active or not, because if I press again the back button, the actionSheet appears again.

anyone know how detect this

import { Component, ViewChild } from ā€˜@angular/coreā€™;
import { Nav, App, Platform, ActionSheetController } from ā€˜ionic-angularā€™;
import { StatusBar, Splashscreen } from ā€˜ionic-nativeā€™;

@Component({
templateUrl: ā€˜app.htmlā€™
})
export class MyApp {
constructor(
public actionSheetCtrl: ActionSheetController,
public platform: Platform,
public app: App) {
this.initializeApp();
}

initializeApp() {
    this.platform.ready().then(() => {
        StatusBar.styleDefault();
        Splashscreen.hide();

        this.platform.ready().then(() => {
            StatusBar.styleDefault();
            Splashscreen.hide();

            //Registration of push in Android and Windows Phone
            this.platform.registerBackButtonAction(() => {
                let nav = this.app.getActiveNav();
                if (nav.canGoBack()){ //Can we go back?
                    nav.pop();
                }else{
                    let actionSheet = this.actionSheetCtrl.create({
                    title: 'Realmente desea salir?',
                    buttons: [
                        {
                        text: 'Si, salir',
                            handler: () => {
                                this.platform.exitApp(); //Exit from app
                            }
                        },{
                            text: 'Cancelar',
                            role: 'cancel',
                            handler: () => {
                                console.log('Cancel clicked');
                            }
                        }
                    ]
                    });
                    actionSheet.present();
                }
            });
        });
    });
}

}

2 Likes

You could make the actionSheet a ā€œthis.actionSheetā€.
Put a check in at the start to see if an actionSheet has been created
this.platform.registerBackButtonAction(() => { if (this.actionSheet) {return;} let nav = this.app.getActiveNav(); if (nav.canGoBack()){ //Can we go back? ...
This acknowledges that it is already visible and hardware back shouldnā€™t do anything at this point.
Then in the handlers set
this.actionSheet = null;

1 Like

Hello! my solution was with a simple confirm alertā€¦

//Registration of push in Android and Windows Phone
this.platform.registerBackButtonAction(() => {
let navv = this.app.getActiveNav();
if (navv.canGoBack()){ //Can we go back?
navv.pop();
}else{
let confirm = this.alertCtrl.create({
title: ā€˜ĀæDeseas salir de +++++++++ App?ā€™,
message: ā€˜El contenido que no tengas guardado, se eliminarĆ”ā€™,
buttons: [
{
text: ā€˜Salirā€™,
handler: () => {
this.platform.exitApp();
}
},
{
text: ā€˜Cancelarā€™,
handler: () => {
//
}
}
]
});
confirm.present();
}
});

its working for me:slight_smile:

Its working for me!: slight_smile:

i have solved this by implementing app minimize plugin and in platform.ready

this.platform.registerBackButtonAction(() => {

  if (!this.nav.canGoBack()) {
    window.plugins.appMinimize.minimize();
  }
  else {
    return this.nav.pop();
  }

});

so that i can control hardware back button , hope this helps

I do not understand very well, how it works. Could you explain it better?

Ok, pay attention to this:

  1. When the Android back button is pressed, cordova fires the backbutton event in the DOM (no rocket science here).

  2. The platform.ready() promise from the Ionic 2 core resolves when the app has finished loading and itā€™s ready to execute custom logic from plugins or you yourself.

  3. If we use 1 & 2 to attach an event listener to the backbutton event, we can detect the tap on such button in hardware (very easy, right? right??).

  4. Inside such event handler we can do whatever we want, in the example i gave, first if clause handles when we are in a non-root page of the app (child pages) and pop's back to the previous page.

  5. Second if handles the case we are in a root page and we havenā€™t pressed the back button before 2000 ms, in such case show a message to user and tell them Press back again to exit the app.

  6. Finally, if the back button is pressed twice in quick succession (2000 ms delay max between presses) then we tell either this.platform or navigator.app to exitApp().

There, done, more explanation and iā€™ll charge you money for making your app.

3 Likes

I just found that if you spam the back button clicking the nav.pop() it will generate an uncaught exception :frowning:
I smell another of the 2^43843 ionic bug.

your page is not active. getting 404

I am no longer using this and donā€™t believe it to be valid any more, therefore I have taken the page down.

How to stop hardware back button in ANDROID
when getting data using LoadingContoller

MyPage.prototype.ScreenLoading = function () {
            this.loader = this.loadingCtrl.create({
                spinner: 'crescent',
                content: 'Loading',
                dismissOnPageChange: true
            });
            this.loader.present();
        };

How can I disable back button on Ionic 3?

1 Like
     this.platform.registerBackButtonAction(() => {
            // disabled back button       });

or you can use Minimize Ionic Plugin

1 Like

Thanks, I managed to make it work.