Ionic Capacitor Hardware Back Button Is Automatically Closing The App
Solution 1:
So, I feel a bit dumb after realizing this, but it is because I had to run the below commands, because I apparently didn't update them when upgrading Capacitor a while back. Make sure all of your plugins are fully updated, yours may be different than mine.
npm install @capacitor/app
npx cap sync
Solution 2:
I had the same issue and I tried installing all the plugins like it says here
npm install @capacitor/app @capacitor/haptics @capacitor/keyboard @capacitor/status-bar
After I finished installing, I still got the error. Also my PushNotifications plugin was not working either.
My problem was I forgot to delete the OnCreate
method from MainActivity.java
. So if you still have the problem after installing the plugins, try to delete OnCreate
method so your MainActivity.java
looks like this:
public class MainActivity extends BridgeActivity {}
See more here.
It also fixed my PushNotifications plugin.
If I understand it correctly, if you have any plugin that is not registered correctly, it will cause this kind of error. This answer also helped me.
Solution 3:
Install capacitor app.
npm install @capacitor/app
Import it.
import { App as CapacitorApp } from '@capacitor/app';
Add back listener if can go back then we can push to back or exit the app.
CapacitorApp.addListener('backButton', ({canGoBack}) => { if(!canGoBack){ CapacitorApp.exitApp(); } else { window.history.back(); } });
Solution 4:
You need to use below code to handle the Hardware back button in Ionic app:
//back button handle
//Registration of push in Android and Windows Phone
let lastTimeBackPress: number = 0;
let timePeriodToExit: number = 2000;
platform.registerBackButtonAction(() => {
//Double check to exit app
if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
//this.platform.exitApp(); //Exit from app
this.appMinimize.minimize().then(() => {
console.log('minimized successfully');
});
} else {
this.toastCtrl.create({
message: this.translate.instant('EXIT_APP_MESSAGE'),
duration: 3000,
position: 'bottom'
}).present();
lastTimeBackPress = new Date().getTime();
}
});
Solution 5:
I have the same issue and adding @capacitor/app to my App worked for debugging puposes. The Problem is, when I build a release app, it still closes the app.
--- EDIT ---
I fixed the issue by building a completely new Ionic App (with the latest versions of everything) and then copying my code. I assume it really had something to do with the installed versions of the Ionic and Capacitor packages
Post a Comment for "Ionic Capacitor Hardware Back Button Is Automatically Closing The App"