4

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)?

jklmnn
  • 481
  • 1
  • 5
  • 11

3 Answers3

5

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

Peter Catalin
  • 1,342
  • 1
  • 14
  • 22
1

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.

Community
  • 1
  • 1
Michael
  • 41,989
  • 11
  • 82
  • 128
0

Take a look at this question: Android onClose event

I think you can achieve what you want with that approach

Community
  • 1
  • 1
Francisco Hernandez
  • 2,378
  • 14
  • 18