How to catch exit app event?

与世无争的帅哥 提交于 2021-01-27 00:35:56

问题


Hy! I need to catch the exit app event in my phonegap application. Actually I want to trigger a looseLife() function if the player tries to cheat and exit the app with minimize and exit from task manager while he already started a new lvl. If he exit it correctly, by pressing the back button it works fine.

I tried onunload or onbeforeunload but these functions get called only if I close the app normally, without minimizing it and closing it from task manager.

The pause function also doesn't help me because it gets triggered also if the screen is locked or when the user switches to another app and than back again.

How to catch the event when the app is minimized and closed in the task manager?


回答1:


I found window.onbeforeunload to work better for cleaning up resources. Possibly off topic but I think window.onbeforeunload wouldn't create any race condition type issues.




回答2:


You can use window.onunload event.

Work for me just fine.




回答3:


I don't think you can catch the user killing your app in the task manager at the time they do it. That's kind of the point of the task manager. However if people use that to cheat in the game you could set a flag in memory to say they are in the game and have the program unset it it they exit normally. If they start the game with the in the game flag still set you'd know they had cheated and could trigger the looseLife() thing?




回答4:


Use the beforeunload event:

window.addEventListener('beforeunload', function(event) {
  console.log(`do something with the event:`, event);
  // most recommended is to emit socket like this (just for example):
  // socket.emit("exit-app", {access_token});
});

This should be emitted and run just before app is getting closed. The most recommended way to do things with this method is emit to server using sockets (Socket.io for example). Don't use HTTP request since HTTP request waits for callbacks or any handshake while sockets no. In this case using sockets is preferable.




回答5:


Use these events:

This event is triggered when the app is put into background.

document.addEventListener("pause", (() => {
  console.log('pause');
}), false);

This event is triggered when the app is returned from background.

document.addEventListener("resume", (() => {
  console.log('resume');
}), false);


来源:https://stackoverflow.com/questions/23409538/how-to-catch-exit-app-event

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