Ionic Capacitor hardware back button is automatically closing the app - android

My current setup is:
#capacitor/core: 3.0.0,
#ionic-native/core: 5.0.7
I'm trying to change the behavior of my app to not close the app, but go back in the navigation stack. To my knowledge, the hardware back button on Android devices did not automatically close the app until I upgraded Capacitor to 3.0.0
What is confusing me though, is how I have absolutely 0 code for handling the back button functionality, and from everything I'm searching online shows the back button doing nothing by default, not automatically closing the app as the default (as mine seems to be doing). I've searched all the project files for anything to do with "platform", "backButton", and "App.Exit" and was unable to find any code that may be causing the app to close.
I've tried subscribing to the back button press event using the below code and it is never ran. The app closes instead of showing the alert dialog. I've changed the priority from 0, 10, and 99 (all priorities listed in the Ionic documentation)
this.platform.backButton.subscribeWithPriority(10, () => {
alert('Back button pressed!');
});

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();
}
});

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

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.

https://stackoverflow.com/a/69084017/19086322
This post work really good for me !!
Before this post i made these commands and after it worked:
npm install #capacitor/app
npx cap sync

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

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();
}
});

for android:
import android.webkit.WebView;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {
//in my case I call it the JS function when I press the back button
#Override
public void onBackPressed() {
WebView webView = getBridge().getWebView();
webView.loadUrl("javascript:pressBack()");
// in Index.html create tag
//<script type="text/javascript">
// function pressBack(){
// alert('yes!!')
// }
//</script>
return;
}
}

Related

Ionic app is “restarted” when I move it to background

Im creating an app and I need to keep working in background but this doesnt work.
Im using:
https://github.com/katzer/cordova-plugin-background-mode
I am on Visual studio with ionic , so I execute:
ionic cordova run android
The app is launched and working. The first view is a Login, I fill the login and this take me to the second view (thit is a tab page).
On this page I add:
import { BackgroundMode } from '#ionic-native/background-mode/ngx';
constructor(private background: BackgroundMode){
this.background.enable();
console.log(this.background.isEnable());
console.log(this.background.isActive());
this.background.moveToBackground();
}
Also, console.log shows that is enable, but not active (that is normal).
The problem is that when I move the app to the background, is “restarted” . I mean that when I open the app from the background it takes me again to the first view where I should do the Login. So this is not working.
This image appears all the times that I open the app for background, and after this, the app is restarted
Am I doing something wrong? Is visual studio?** How can I solve it?**
Thanks!
Use plugin Background Mode
ionic cordova plugin add cordova-plugin-background-mode
npm install #ionic-native/background-mode
Then use it like this:
import { BackgroundMode } from '#ionic-native/background-mode/ngx';
export class AppComponent {
constructor(private backgroundMode: BackgroundMode) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.backgroundMode.enable();
});
}
}

Ionic 4: Hardware Back Button Reloading Application

Working on a Project and stuck in an Issue:
Hardware Back Button Reloading Application (I am using Angular Router in this application).
My Code to Exit Application:
ionViewDidEnter(){
this.subscription = this.platform.backButton.subscribe(()=>{
navigator['app'].exitApp();
});
}
ionViewWillLeave(){
this.subscription.unsubscribe();
}
While same logic Working in other applications. but in this application its reloading the application not exiting it.
P.S: i have also tried it to put in platform.ready() but no luck.
With IONIC 4, there is new method subscribeWithPriority developed to handle race between soft & hard back button. Try modifying your code like below:
this.platform.backButton.subscribeWithPriority(1, () => {
navigator['app'].exitApp();
});
subscribeWithPriority() stops the propagation of the event after its execution and if we subscribe with high priority and execute our prefered navigation instead of default one then it is going to work as you want.
More reference docs for details:
https://github.com/ionic-team/ionic/commit/6a5aec8b5d76280ced5e8bb8fd9ea6fe75fe6795
https://medium.com/#aleksandarmitrev/ionic-hardware-back-button-nightmare-9f4af35cbfb0
UPDATES:
Try using this new version of exitApp cordova plugin. I haven't
tried myself but looks promising from popularity.
Also try to empty the page stack from Navcontroller or go to your home screen, seems like that's causing the reload for app with sidemenu's & tab pages... this.navCtrl.pop() / this._navCtrl.navigateBack('HomeScreen'), and then call exitApp.
NOTE: Tabs & SideMenu as those have its own routing module does create lot of complexity with app navigation.
Solved:
As Mention by #rtpHarry template of SideMenu / Tabs have History which leads application to Reload it self on root page. i was able to solve this by clearing History.
ionViewDidEnter(){
navigator['app'].clearHistory();
}
on Your Root Page just Clear your history and your Hardware Back Button will close the Application instead of Reloading it.
Do you have a sidemenu in your app? I'm just curious because this seems to be when I get this problem as well.
If you look in your inspector, you will see that window.history has a length of 1.
I don't see it in some of my apps, but the app that I have a side menu setup acts this way - on the homepage if you press back the screen goes white then it reloads the app.
Like I say, looking in the inspector shows that there is a history to step back to, which it is trying to do, and whatever that history step is, it just pushes it forward back to the homepage, which made me wonder if it was the sidemenu setting up its own control of the navigation system.
I've probably said some poorly worded terminology but as I haven't solved this myself I thought I would just let you know what I had found... hopefully it helps you move forward.
In my scenario, I wasn't even trying to do the exit on back code - I just noticed that the app would appear to "reboot" if I kept pressing back.
This explain the solution on Ionic 5 (and 4.6+ too I think).
private backButtonSub: Subscription;
ionViewDidEnter() {
this.backButtonSub = this.platform.backButton.subscribeWithPriority(
10000,
() => {
// do your stuff
}
);
}
ionViewWillLeave() {
this.backButtonSub.unsubscribe();
}
also keep
IonicModule.forRoot({
hardwareBackButton: true
}),
to true (default) in your app.module.ts
Sources:
https://www.damirscorner.com/blog/posts/20191122-CustomizingAndroidBackButtonInIonic4.html
The Doc

Ionic onHardwareBackButton implementation

I'm trying to control how the android hardware back button behaves in my app. I had it all working but now I can't reproduce it. The code I'm using is in app.js. I'm expecting the back button to do nothing but write to the console.
.run(function($ionicPlatform) {
$ionicPlatform.onHardwareBackButton(function() {
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!")
});
Can any one see what the problem is? I'm running ionic CLI v1.7.11. I'm running the code with ionic view on android
You can find full details, including a full working solution for both hard & soft back buttons at my related post:
Ionic override all BACK button behaviour for specific controller
To summarise how I handled the hardware back button, the trick is to register an action for the Back button, using code like this:
var doCustomBack= function() {
// do something interesting here
};
// registerBackButtonAction() returns a function which can be used to deregister it
var deregisterHardBack= $ionicPlatform.registerBackButtonAction(
doCustomBack, 101
);
$scope.$on('$destroy', function() {
deregisterHardBack();
});
The actual setting is done in that second block calling $ionicPlatform.registerBackButtonAction().
This returns a method that can be called to deregister the action later on if you want to.
It was a ionic view problem. Seems it does not support this.

back button in cordova/phongap meteor build for android won't close application consistently

I've built and app for android with meteor and phonegap/cordova:
https://play.google.com/store/apps/details?id=com.idqkd3gsl4qt51152xgy
It works decently OK (especially given that I'm not really a programmer), but one UX issue I've been struggling with is that the app will not consistently close when pressing the back button on my phone. Every once in a while it works on the first press, but most of the time I have to jam it 5-6 times in a row to get the app to close.
I'm using the latest iron-router. The rest of the packages I'm using don't seem particularly relevant to this issue but they are as follows just in case:
standard-app-packages
coffeescript
natestrauser:font-awesome#4.1.0
accounts-password
aldeed:autoform
aldeed:collection2
nemo64:bootstrap
less
alanning:roles
joshowens:accounts-entry
mrt:accounts-admin-ui-bootstrap-3
mizzao:jquery-ui
iron:router
sacha:spin
raix:push
mizzao:bootboxjs
meteorhacks:kadira
bootstrap3-media-query
the repo can be seen here: https://github.com/The3vilMonkey/BrewsOnTap
I can't specify the exact reason for this issue other than it seems like at startup there is a sort of redirect happening with cordova apps. Best solution I've found is to catch the popstate event and when you get back to the beginning exit or suspend the application.. I prefer suspend that way when the user comes back to the app it doesn't start it's lifecycle from the beginning.
if(Meteor.isCordova){
Meteor.startup(function(){
window.onpopstate = function () {
if (history.state && history.state.initial === true){
navigator.app.exitApp();
//or to suspend meteor add cordova:org.android.tools.suspend#0.1.2
//window.plugins.Suspend.suspendApp();
}
};
});
}
One caveat that got me when I first used this was redirecting to a login page if the user wasn't logged in.. If you're using this method in an app that does this, you'll want to switch to rendering the login page in place rather than redirecting otherwise your app will exit/suspend immediately.
In my case, I made a mix of the two previous answers so that it works well.
document.addEventListener("backbutton", function(){
if (history.state && history.state.initial === true) {
navigator.app.exitApp();
} else {
history.go(-1);
}
});
While Kelly's answer does work, it did not end up being functionally correct for my particular situation. An important point to note about that solution is that it will exit as soon as the back button causes you to return to the initial page and not when you press the back button while on the initial page.
Ultimately I used cordova's backbutton listener to see if the backbutton was pressed:
if Meteor.isCordova
Meteor.startup ->
document.addEventListener("backbutton", ->
if document.location.pathname is "/"
navigator.app.exitApp()
else
history.go(-1)
and then if I am at the root of my application I exit/suspend, otherwise I simply go back in the history.
Using the backbutton event listener does seem to override it's default functionality so calling history.go(-1) was necessary in my case.
Also note that this solution would break if you want a true history that could go back through the history (potentially hitting the root of your application multiple times) before existing on the initial entry point. A combination of my answer and Kelly's might work for that. I find that while that might be the expected behavior for websites, it isn't really for mobile apps.
Here's a meteor package available to do this for you as well:
https://github.com/remcoder/fix-back-button-android
EDIT:
I actually went ahead and forked that repo, fixed the cordova plugin dependency issues, and used Kelly's code instead of the code from the original repo, find my fork here:
https://github.com/tripflex/fix-back-button-android
Or install in Meteor using:
meteor add tripflex:fix-back-button-android
I can confirm it works correctly, when adding via GitHub method described below, and using Kelly's answer for detecting the root page (do not use the example on the GitHub repo).
I'm no meteor expert as well (but am a full time dev), but going off of Kelly's answer, I would move the check for isCordova inside the Meteor Startup (as i'm sure you will have more startup code as your app progresses)
Meteor.startup(function(){
// Mobile specific code
if(Meteor.isCordova) {
window.onpopstate = function () {
if (history.state && history.state.initial === true) {
navigator.app.exitApp();
//or to suspend meteor add cordova:org.android.tools.suspend#0.1.2
//window.plugins.Suspend.suspendApp();
}
};
}
// Any other startup code below here
});
EDIT: If you decide you want to use the cordova suspend package, it will not work like most cordova plugins in Meteor due to the plugin not existing in npm, so this will NOT work:
meteor add cordova:org.android.tools.suspend#0.1.2
You MUST add it like this using the GitHub repo:
meteor add cordova:org.android.tools.suspend#https://github.com/Lamerchun/org.android.tools.suspend.git#0dbb52cca0244ba22a8c7975895f0f45d2e9a4a9

Phonegap window.open does not work on Android

I have an iOS/Android app built on cordova 2.6 and jqm 1.3. I need to open a link to an external website after the user clicks on a button. The code I am using is:
var ref = window.open('http://google.com','_self','location=yes');
ref.addEventListener('loadstart',function(event) {
console.log('load started');
});
ref.addEventListener('loadstop',function(event) {
console.log('load stopped');
});
ref.addEventListener('loaderror',function(event) {
console.log('load error = ' + JSON.stringify(event));
});
On iOS everything performs like I would expect. A new browser window opens with the google website loaded. But I cannot get anything to to load in Android. When I click on the button, nothing happens. I have put in console statements before and after the window.open, so I know the code is at least being executed.
My config.xml should be wide open for white listed sites:
<access origin=".*"/>;
I have tested on a Nexus 7 (android 4.2) and an android 2.2 emulator with the same results on both.
Does anyone know why window.open would not be firing correctly on android?
It looked like it was a problem with 2.6 loading plugins on Android. I upgraded to 2.7 and everything started to work.
Perhaps it's a solution to use the ChildBrowser plugin? This gives you a bit more control over the operation itself, while still preserving platform compatibility between iOS and Android.
In most cases, I use something like the following snippet to use the childbrowser to display an external page.
function openBrowser(url) {
// determine if the childbrowser plugin is available
var useChildBrowser = ('plugins' in window && window.plugins.childBrowser);
if (useChildBrowser) {
popup = window.plugins.childBrowser;
popup.showWebPage(url, { showLocationBar: false, showAddress: false });
} else {
popup = window.open(url, 'Share', "['width=600px', 'height=400px', 'resizable=0', 'fullscreen=yes']");
}
}
Note that this falls back to using window.open if the ChildBrowser plugin isn't available, so you won't break anything else with this. Could be worth a shot, perhaps?

Categories

Resources