Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect application refocus event

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.

like image 225
vaugham Avatar asked Mar 14 '13 12:03

vaugham


3 Answers

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');
}
like image 76
mbokil Avatar answered Nov 07 '22 14:11

mbokil


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à

like image 24
vaugham Avatar answered Nov 07 '22 13:11

vaugham


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.

like image 2
ex3v Avatar answered Nov 07 '22 13:11

ex3v