I need to know each time the user is starting to use the application.
Case 1 (OK) : The app is not started.
The user starts the application from scratch.
I add a listener on the app's bootstrap, and I am aware when it starts.
Case 2 (TODO) : The app has been started but it's not active anymore
The user reload the application from the taskbar.
I want to know when the application comes from the taskbar to the foreground (like a alt+tab).
This is tricky to catch, because the app is still running and I don't know which event to listen to. In fact, I don't even know how to name this behaviour.
There is an event for app resume and pause in Cordova so you don't need to edit the Cordova class files. Below is working code I am currently using in an app for iOS/Android.
window.onload = function() {
//only fired once when app is opened
document.addEventListener("deviceready", init, false);
//re-open app when brought to foreground
document.addEventListener("resume", init, false);
//trigger when app is sent to background
document.addEventListener("pause", onPause, false);
}
function init() {
console.log('device ready or resume fired');
}
An ios-app developper accepted to help me. His answer suits me very well, as it seem clean et reusable. So I will produce it here :
The "app come to foreground" event can be catched through the applicationWillEnterForeground event. Phonegap/Cordova allows to call javascript functions through the Cordova classes. The webView object has a dedicated method to launch js scripts.
So I opened the file Projet/Classes/Cordova/AppDelegate.m :
- (void)applicationWillEnterForeground:(UIApplication *)application {
NSLog(@"applicationWillEnterForeground: %@", self.viewController.webView);
[self.viewController.webView stringByEvaluatingJavaScriptFromString:@"notifyForegroundEvent();"];
}
And I added the notifyForegroundEvent() method somewhere in the root of my js files :
var notifyForegroundEvent = function() {
console.log('notifyForegroundEvent()');
// Do something here
}
Et voilà
As I saw on facebook (destkop, not mobile) some time ago, they check mousemove to determine if received chat message should be marked as read or not. I know that that isn't the solution, but it might point you in a good direction. I would also check what happens to the input focus, when you switch to other app. Maybe it blurs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With