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();
});
}
}
Related
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;
}
}
What do I have to do to make the phone take the background of my Ionic application? It always appears in black.
Change your statusBar settings.
In app.component.ts you can use the following values:
StatusBar.styleDefault
StatusBar.styleLightContent
StatusBar.styleBlackTranslucent
StatusBar.styleBlackOpaque
For example:
initializeApp() {
this.platform.ready().then(() => {
//this.statusBar.styleDefault();
this.statusBar.styleBlackTranslucent();
this.splashScreen.hide();
...
Other options you can find at https://github.com/apache/cordova-plugin-statusbar
I'm developing a hybrid app using Ionic 4. Ionic just like other html5 based apps runs as a webview in MainActivity. using capacitor I've imported my app to android studio and I've created a SecondActivity. How can I go to SecondActivity by clicking a button inside first activity(MainActivity) (which is an Ioninc page and for sure an html webview).
So far i've tried different method to achieve this but no luck.
I've created a cordova plugin following this tutorial:
Start android activity from cordova plugin
it works prefect in cordova application but I was not successful to import it into Ionic.
also I've tried Capacitor and apparently accessing native code using capacitor should be very easy but unfortunately I've had no luck so far.
https://capacitor.ionicframework.com/docs/plugins/android
after struggling a lot! here is the answer:
the plugin that I mentioned actually works cool in cordova and to bring it to ionic4 (as the clobbers of plugin is "PluginName", you have to declare and use it in your typescript)my code is as follows (home.page.ts):
import { Component } from '#angular/core';
declare var PluginName: any;
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
goToCustomActivity(){
PluginName.new_activity();
}
}
and in your home.page.html:
<ion-content>
<ion-button (click)="goToCustomActivity()">go to custom activity</ion-
button>
</ion-content>
I hope this help someOne.
and special thanks to original coder of plugin "Ijas Ahamed N"
you can find instructions to write plugin here:
https://www.ijasnahamed.in/2016/11/start-android-activity-from-cordova.html
and here is the stackoverflow (be aware! step to create package.json is omitted in stackoverflow!)
Start android activity from cordova plugin
You can do it by taking use of WebView.addJavaInterface. Just write a Android class in Java (to launch a the Activity you want), and inject the object into WebView context by calling WebView.addJavaInterface(). When the HTML button is clicked, you call the injected JS method to launch the Activity.
The Activity Launcher:
class MyJsInterface {
#JavascriptInterface
public String launchActivity() {
// ...;
}
}
Inject it:
webview.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new MyJsInterface(), "AndroidInterface");
webView.loadUrl(...);
In your web page:
<button onclick="AndroidInterface.launchActivity()">Launche Activity</button>
I have created a small game and created build using Intel XDK. I installed it in device and can see the splash screen. I tried what is mentioned in other topics but unable to remove the splash screen.
function onDeviceReady(){
if( navigator.splashscreen && navigator.splashscreen.hide ) {
navigator.splashscreen.hide();
}
if( window.intel && intel.xdk && intel.xdk.device ) {
if( intel.xdk.device.hideSplashScreen ) {
intel.xdk.device.hideSplashScreen();
}
intel.xdk.device.setRotateOrientation("landscape");
intel.xdk.device.setAutoRotate(false);
intel.xdk.device.hideStatusBar();
}
}
document.addEventListener("intel.xdk.device.ready", onDeviceReady, false);
This is how it looks initially when I launch the app.
I have this plugin added in the project
cordova-plugin-splashscreen
Please help me resolve this issue.
Received this answer on XDK forum
The purpose of the splashscreen is to hide the details of the
initialization process (even before your device ready fires). The
splashscreen you see is the default cordova splash screen, you can
replace it by your own graphics. You can upload custom splashscreen
through Launch Icons and Splash screens on Projects page. The
hidesplashscreen() method will hide the splashscreen that is displayed
at the initialization and the contents of your app will appear (which
happens when device is ready).
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