Reputation: 133
I am working on my application but stuck in one problem which is hardware backbutton. I need when user click on backbutton so it will not back the app or close just show some toast.
And on double tap close the app. But its not working no toast is showing and hardware back button is working .
This is my code in app.component.ts
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
// this does work
this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
if (outlet && outlet.canGoBack()) {
outlet.pop();
} else if (this.router.url === '/wallet') {
if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
// this.platform.exitApp(); // Exit from app
navigator['app'].exitApp(); // work for ionic 4
} else {
this.toast = this.toastCtrl.create({
message: 'double tap to exit.',
duration: 2000,
position: 'bottom'
}).then((toastData)=>{
console.log(toastData);
toastData.present();
});
this.lastTimeBackPress = new Date().getTime();
}
}
});
});
}
Its working fine in some ionic version but my version is ionic 6.0.1
I have try with dfferent answers this is working but how can i enable double tap close int it ? now its not closing or back on hardware button but i need to clsoe app on double tap
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
// this does work
this.platform.backButton.subscribeWithPriority(9999, () => {
document.addEventListener('backbutton', function (event) {
event.preventDefault();
event.stopPropagation();
console.log('hello');
}, false);
});
});
}
Upvotes: 0
Views: 2654
Reputation: 575
Below code worked for me. within initializeApp()
add below snipet
this.platform.backButton.subscribe(() => {
if (Date.now() - this.lastBack < 500) { // logic for double tap: delay of 500ms between two clicks of back button
navigator['app'].exitApp();
}
this.lastBack= Date.now();
});
Define private lastBack = Date.now();
as a variable in your Component
Upvotes: 0
Reputation: 1366
Refer to this code and make changes if required as per your requirement.
Under initializeApp()
call a function backbuttonSubscribeMethod()
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.backbuttonSubscribeMethod();
});
}
Define your method
backbuttonSubscribeMethod() {
let a = 0;
this.platform.backButton.subscribe(() => {
a++;
if (a == 2) { // logic for double tap
navigator['app'].exitApp();
}
});
}
Unsubscribe it under this
ngOnDestroy() {
this.platform.backButton.unsubscribe();
}
Upvotes: 2