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)?
3 Answers
Whenever your app is about to get "closed" it's going to call some methods in the activity life cycle.
This is from 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.
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.
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

- 1,342
- 1
- 14
- 22
-
You're welcome. There is a very nice Android course on udacity.com, just browse trough the catalog they have. – Peter Catalin Nov 17 '15 at 12:04
The onTaskRemoved() callback is probably what you want. According to the Android dev reference:
This is called if the service is currently running and the user has removed a task that comes from the service's application
This question also has some interesting discussion about this.
Take a look at this question: Android onClose event
I think you can achieve what you want with that approach

- 1
- 1

- 2,378
- 14
- 18