Detect application refocus event

时间秒杀一切 提交于 2020-01-12 19:06:31

问题


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.


回答1:


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



回答2:


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à




回答3:


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.



来源:https://stackoverflow.com/questions/15408783/detect-application-refocus-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!