java 应用关闭时的Android调用功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33740686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android call function on app close
提问by jklmnn
Is it possible to create a function that is being called when the app is closed in Android (e.g. when you go to the running app view and swipe an app away)?
是否可以创建一个在 Android 中关闭应用程序时调用的函数(例如,当您转到正在运行的应用程序视图并滑动应用程序时)?
回答by Peter Catalin
Whenever your app is about to get "closed" it's going to call some methods in the activity life cycle.
每当您的应用程序即将“关闭”时,它都会调用 Activity 生命周期中的一些方法。
This is from developer.android.com:
这是来自 developer.android.com:
When your activity receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, so it's important you use onStop() to release resources that might leak memory.
当您的 Activity 收到对 onStop() 方法的调用时,它不再可见,并且应该会在用户不使用它时释放几乎所有不需要的资源。一旦您的活动停止,系统可能会在需要恢复系统内存时销毁实例。在极端情况下,系统可能会简单地终止您的应用进程,而不会调用 Activity 的最终 onDestroy() 回调,因此使用 onStop() 释放可能会泄漏内存的资源非常重要。
Although the onPause() method is called before onStop(), you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.
尽管 onPause() 方法是在 onStop() 之前调用的,但您应该使用 onStop() 来执行更大、更多 CPU 密集型的关闭操作,例如将信息写入数据库。
http://developer.android.com/training/basics/activity-lifecycle/stopping.html#Stop
http://developer.android.com/training/basics/activity-lifecycle/stopping.html#Stop
You can take a look at the life cycle here:
您可以在此处查看生命周期:
http://developer.android.com/images/training/basics/basic-lifecycle-stopped.png
http://developer.android.com/images/training/basics/basic-lifecycle-stopped.png
回答by Francisco Hernandez
Take a look at this question: Android onClose event
看看这个问题:Android onClose event
I think you can achieve what you want with that approach
我认为你可以用这种方法实现你想要的
回答by Michael
The onTaskRemoved()callback is probably what you want. According to the Android dev reference:
该onTaskRemoved()回调可能是你想要的东西。根据 Android 开发参考:
This is called if the service is currently running and the user has removed a task that comes from the service's application
如果服务当前正在运行并且用户已删除来自服务应用程序的任务,则调用此方法
This questionalso has some interesting discussion about this.
这个问题也有一些有趣的讨论。