Phonegap - Bring from background to foreground - android

I'm developing my team along with an application that must run in the background when an event called by sockets should put the application in the foreground .
The application must come to foreground similar to viber or whatsapp call. I stopped at this point. My application can now call an audio and vibrate, but I have to draw the screen to the foreground.
I'm using version 5.1.1 phonegap.
I am this plugin: https://github.com/katzer/cordova-plugin-background-mode
Could someone give me a hand? Very grateful this already.

I found a way! Using the "toForeground" plugin. https://github.com/caioladislau/cordova-toforeground
cordova.plugins.backgroundMode.enable();
cordova.plugins.backgroundMode.onactivate = function() {
setTimeout(function(){
toForeground("MainActivity", "com.me.myapp", function() {
navigator.notification.vibrate(1000);
}, function(){
navigator.notification.vibrate(5000);
});
}, 4000);
};
Note where it is called in:
toForeground(mainClassName, packageName, successFunction, errorFunction);
To find the "mainClassName" and "packageName" I searched: platforms/android/src/com/me/myapp/MainActivity.java, and I found:
package com.me.myapp;
import android.os.Bundle;
import org.apache.cordova.*;
public class MainActivity extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
loadUrl(launchUrl);
}
}

I have used this plugin instead of developing one for my own, its a forked repo
https://github.com/suhail339/cordova-bring-to-front
Keep in mind to install from Cordova CLI, visual studio plugin
installer might create problem.

Related

How do I configure Android settings in a Vue/Capacitor app?

I'm building an application for web/Android with Vue+Capacitor. What's the correct way to manipulate the Android part?
For example, I'd like the screen to not turn off through idle. Apparently, the way to do this is to put
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
in the MainActivity. But since the Android part gets built again all the time it doesn't really make sense to edit it directly (or maybe I'm mistaken here somehow?)
So how do I achieve something like this?
Edit for clarification:
This is the MainActivity:
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
As you can see it does absolutely nothing besides extending BridgeActivity
This is the (generated!) onCreate of BridgeActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bridgeBuilder.setInstanceState(savedInstanceState);
getApplication().setTheme(getResources().getIdentifier("AppTheme_NoActionBar", "style", getPackageName()));
setTheme(getResources().getIdentifier("AppTheme_NoActionBar", "style", getPackageName()));
setTheme(R.style.AppTheme_NoActionBar);
setContentView(R.layout.bridge_layout_main);
/* The initally mentioned line here works but gets overwritten*/
}
You can just use this community plugin: https://github.com/capacitor-community/keep-awake.
This way you don't have to change the native code.
import { KeepAwake } from '#capacitor-community/keep-awake';
const keepAwake = async () => {
await KeepAwake.keepAwake();
};
const allowSleep = async () => {
await KeepAwake.allowSleep();
};
Once you run npx cap add android, the native project gets created and it’s never modified by capacitor, so you can make any changes you want in the MainActivity.java file or any other files (except the ones that start with “automatically generated, do not edit” or similar messaging).

Ionic Capacitor hardware back button is automatically closing the app

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

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

How to change android activity by clicking a button in (ionic) webview?

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>

How to load and navigate a website within a Cordova webview

Hello I have built my website, was looking forward to have an app for my responsive website... I went with android webviews but it posed problems with opening filechooser... So I went with Cordova after doing a lot of research. I succeeded in creating a Cordova application an imported it to Android studio. My problem is, when my landing page opens clicking any other link opens the default browser... I don't want this behavior I want all links to open within the app(Using Cordova's webviews)...thanks in advance.
NOTE:Am using Cardova to open a completely remote website no local stuff.
My MainActivity.java look like this
package com.noel.myapp;
import android.os.Bundle;
import org.apache.cordova.*;
public class MainActivity extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
loadUrl("http://www.mywebsite.com");
}
}
The inAppBrowser adds an additional address bar at the top. Instead if you just want in app navigation you can use this solution (borrowed from comment section of this answer)
Add this line in your config.xml file
<allow-navigation href="*://*.example.com/*" />
and inside your index.js add something like this
receivedEvent: function(id) {
// other code
window.location = "https://www.example.com
}
(Although this being an old thread sharing anyways if someone else comes across this)
use cordova-plugin-inappbrowser for that
cordova docs for inappbrowser is here.
after device is ready (deviceready event)
use
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
after adding the plugin.
basic example is here

Categories

Resources