简体   繁体   English

如何检测用户何时退出我的应用程序?

[英]How can I detect when a user exit my app?

I'm writing an android app and I want to remove the user from an array when he exit the app. 我正在编写一个android应用程序,我想在用户退出应用程序时将其从数组中删除。 I tried using the onStop() method, but it's not woking as I desire, because whenever an activity changes, the user is removed from the array. 我尝试使用onStop()方法,但是并没有按照我的意愿进行唤醒,因为每当活动发生变化时,都会从数组中删除用户。

I need a way to execute a method when the user has removed the app from "recent activities". 当用户从“最近的活动”中删除该应用程序时,我需要一种执行方法的方法。 Any suggestions on the matter? 有什么建议吗?

You can track the back key so when the user presses it to exit the app you do what you want. 您可以跟踪返回键,以便当用户按下该键退出应用程序时,您可以执行所需的操作。

 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
       if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        //YOUR CODE HERE
    finish(); //<<<------MUST BE USED SO THAT THE BUTTON WILL ACTUALLY FINISH THE APP
        }
  return super.onKeyDown(keyCode, event);
   }

Otherwise you can try the onPause() method instead of the onStop. 否则,您可以尝试使用onPause()方法代替onStop。 Android doesnt recommend using the onStop to save data etc. I think though that the back key is best Android不建议使用onStop来保存数据等。我认为尽管Back键是最好的

I need a way to execute a method when the user has removed the app from "recent activities" 当用户从“最近的活动”中删除应用程序时,我需要一种执行方法的方法

When you swipe an app from the list, it actually just stops all the app's services (and not the app itself!). 当您从列表中滑动某个应用程序时,它实际上只是停止了该应用程序的所有服务(而不是应用程序本身!)。 You may want to consider creating a service just for this purpose so that when the service is killed, you are notified via onTaskRemoved . 您可能要考虑为此目的创建服务,以便在服务被杀死时,通过onTaskRemoved通知您。

You can read some more here 你可以在这里阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM