I am using ionic framework to build my app, which seems working fine as per my requirement.
Now i close my app and reopen again it maintaining the state which is also fine.
Now my question is
1) Does app.js files run each time when my app is open ?
i tried to add alert in app.js , which works only first time
Is this right or wrong ?
2) I want to run a particular function each time when my app get started. Is there is any way to do this ?
Thanks
There is a very large documentation which gets upgraded every time a new major version of Cordova/Phonegap is released. You can find that documentation here: Cordova Documentation 5.0
It describes an event which is called every time your "device is ready". It is called onDeviceReady. To use this event you need an onDeviceReady-EventListener. The documentation for the EventListeners can be found here: Events in Cordova
You can add that EventListener with this command:
document.addEventListener("deviceready", yourCallbackFunction, false);
Like Zain described in the comments, there is a difference between exiting the application and pausing it, there is also another EventListener which gets called when the user pauses the application. It can be attached to your application with:
document.addEventListener("pause", yourCallbackFunction, false);
So you could create a function which gets called when those two listeners are fired like this:
onDeviceReady
document.addEventListener("deviceready", deviceIsReady, false);
function deviceIsReady() {
alert('Your device is ready!');
}
pause
document.addEventListener("pause", onPause, false);
function onPause() {
alert('Your application is paused');
}
Alternatively, if the alert is not called when the application is paused, you could add the Cordova Plugin Console and call the onPause function with this content:
function onPause() {
console.log('Your application is paused');
}
Please let me know, if this solves your question or if you need further assistance.
Related
When we creating a watcher in cordova, we need to fire it after the device is ready.
In ionic framework we are using the following code to do that.
$ionicPlatform.ready(function() {
$cordovaPlugin.someFunction().then(success, error);
});
I want to know what this code exactly doing..? What is someFunction() and what is done with .then(success, error);
This is a question which could simply be answered by the existing cordova documentation:
Cordova Documentation - DeviceReady Event
I would also recommend you to read some tutorials or guides on how to start with hybrid app development.
success() will get called, when the device has fired the device ready event.
errorshould be self-explaining.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
document.addEventListener("backbutton", backButtonEvent, false);
}
function backButtonEvent() {
var currentUrl=window.location.hash;
if(currentUrl=='#/homePage' || currentUrl=='#/'){
navigator.app.exitApp();
}
else{
history.go(-1);
navigator.app.backhistory();
}
}
Iam using ionic framework and phone gap.. here when i click device backbutton from home page its just minimizing that app not exiting. How can i exit my app??
In case you mean by minimizing that app that the application goes to the background (is not the active application but it is still in the list of running applications). In case that is what you mean, please notice that this is the normal behavior in Android and many Mobile OS.
Terminating (exiting if you prefer) the application is not under the control of the application developer. It is completely managed by the OS (Android in this case). So, what you have is the normal behavior for apps under Mobile OS.
Instead of terminating the application as you would do under old OS (Linux, Windows and alike), you have to manage the lifecycle of the application: pause, resume, ...
Install plugin https://github.com/ZhichengChen/cordova-plugin-android-home.
Implement 2 handlers for plugins.
Use the bellow code to exit the application.
exitApp:function() {
app.exitApp();
}
This is a bit of a long shot but I'm going to ask to see if others have experienced anything similar.
We are creating a cordova ( 3.3.0 ) iOS / Android app. On iOS all is well.
On Android ( testing with Android emulators or a Samsung 8 Tab 4.2.2 ) when navigator.notification.confirm is called we quite often see the callback not fired back in JS after one of the confirm dialog buttons has been pressed.
Debugging Cordova ( native side ) we see the button pressed, the native dialog dismissed and the callback message added to the JsMessageQueue. But the queue doesn't seem to be serviced until something else forces it to be. For example, another call to navigator.notification.confirm would then causes the queued message to run.
We've put extra logging into the NativeToJSMessageQueue on setPaused to see if something was not restoring the pause but it looks ok.
I'm sure we've done something to upset it. Is there anything fundamental that basically stops the message queue from being processed that we should be aware of ? Something that on the javaside would cause cordova on Android not to check the queue ?
We don't see the problem on iOS but I'm sure this is because it doesn't use the same message despatch system as Android.
Sorry for the lack of code or any more info. I was hoping this may ring a few bells.
Update :
We've done a little more debugging and it appears to have something to do with fullscreen mode. If set in fullscreen mode ( via the config ) or native code the events do fire.
If fullscreen mode is set to false the callback event is left in the queue, and fired as soon as the button is pressed a second time.
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
function testButton()
{
navigator.notification.confirm('You are the winner!',onConfirm, 'Game Over', ["Butt1","Butt2"]);
}
This has been fixed in Cordova 3.6.0.
Anyone can explain me how keepRunning works in the config.xml for Android.
I mean, I don't want to know how to write the instruction but how does it work, how does it affect the execution of the Android app ? Does it create an Service in background ?
If anyone can find the source where we can see how does it work, that will be great
Thanks.
Edit : I try to analyze the generated code, analyze the RAM, services and processus in the setting of Android. And my conclusion is..... that do nothing.
If you try to make a app which track the user with GPS, dont use Cordova. To track the user correctly, you need to make a Service with the START_STICKY option. So, it's in native code. you lost the interest of the CrossPlatform because you have to recode the service for all platforms and in my opinion, the communication between Native Service and Cordova App is not easy.
In conlusion, if you use Cordova, you have to know you can't use the power of all native, you have to make choise :
- easy dev (subjective) and crossplaform (really crossplatform ?)
and
- Native dev with its power and no compatibility problems but you have to make one app for one platform
I'm not a JS/Cordova developer, I'm an Android developer. Once I worked on a Cordova plugin, faced some issues and did some investigations on the subject.
General purpose of keepRunning flag is to indicate if JS timers should be stopped when the app is paused (goes to background). Answering your question: no, it doesn't create any new Service. Existing design is quite plain in this regard.
The keepRunning flag is defined in CordovaActivity.java as follows:
// Keep app running when pause is received. (default = true)
// If true, then the JavaScript and native code continue to run in the background
// when another application (activity) is started.
protected boolean keepRunning = true;
Its main purpose is to disable JS timers when Cordova app is paused, in CordovaWebView.java:
public void handlePause(boolean keepRunning)
{
LOG.d(TAG, "Handle the pause");
// Send pause event to JavaScript
this.loadUrl("javascript:try{cordova.fireDocumentEvent('pause');}catch(e){console.log('exception firing pause event from native');};");
// Forward to plugins
if (this.pluginManager != null) {
this.pluginManager.onPause(keepRunning);
}
// If app doesn't want to run in background
if (!keepRunning) {
// Pause JavaScript timers (including setInterval)
this.pauseTimers();
}
paused = true;
}
Note that plugins are also notified via PluginManager, so in theory they can handle app paused events, to stop (or not) their activity in background, depending on keepRunning flag.
In my case I had an issue/bug when keepRunning was true, but JS timers were stopped anyway. It happened because there is additional functionality related to that flag, in CordovaActivity.java:
/**
* Launch an activity for which you would like a result when it finished. When this activity exits,
* your onActivityResult() method will be called.
*
* #param command The command object
* #param intent The intent to start
* #param requestCode The request code that is passed to callback to identify the activity
*/
public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
this.activityResultCallback = command;
this.activityResultKeepRunning = this.keepRunning;
// If multitasking turned on, then disable it for activities that return results
if (command != null) {
this.keepRunning = false;
}
// Start activity
super.startActivityForResult(intent, requestCode);
}
When Cordova app launches another Android activity, main Cordova activity (screen with WebView) goes to background and is therefore paused. In my case it was made via Google Maps plugin which started GM screen over Cordova app.
The code above turns off keepRunning flag, and it means that JS timers are stopped anyway when the called activity appears (in CordovaActivity.onPause method) regardless keepRunning is true or false!
It looks like a kind of trick implemented for some unclear (and not documented) purpose, I do not know its context. In my case it caused a bug, and I just removed keepRunning handling in startActivityForResult, recompiled Cordova and it worked OK.
ADDED: About using a Service for GPS - you are quite right, I agree. As an Android developer with relevant (GPS) experience I can say that a right approach (and possible the only acceptable) is to use a service for that. As far as I know Cordova doesn't provide any functionality for it, so I think it should be made via a plugin. I mean you can write native Android code for GPS functionality (implemented as a Service) and access it from JS code. I believe it is a common solution in Cordova for such cases.
Perfect answer, helped me a lot! I was searching for the solution to the problem for 2 days now.
In my case I'm currently developing a cordova plugin for login purposes. For the login I use an external form which I load in a webview. For two days now I was struggling with the fact that the "Password forgotten" link and every other link on the page I loaded was working, but I wasn't able to submit my form. Only when I hit the back button and through this finished the intent holding the webview, it did submit and proceed.
Turns out that the keepRunning handling was the only problem here. In the end I replaced: `
cordova.startActivityForResult(this, intent, 0);
by:
cordova.setActivityResultCallback(this);
cordova.getActivity().startActivityForResult(intent, 0);
which basically fulfills the whole job Cordova's startActivityForResult would do The only thing that's left out is the whole keepRunninghandling which messed up my plugin in the first place.
Thanks again, Mixaz!
I tested navigator.online and it worked until I built the app with PhoneGap, after that, navigator.online always returned true.
Does anybody know how can I un-cache or refresh this value? I need it on "on click" events.
I was also facing this issue while I was developing an application.
What I used is:
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
These events will be fired when the device is disconnected or connected to internet on the fly.
You can store some global variables in the function
function onOnline(){}
and
function onOffline(){}
Than check the values of those global variables and do whatever you want to according to the value.