1

I have some resources to clean up(at the server side) when user closes the app by swiping the app from all open apps or pressing back button. My onDestroy is not being called in these above cases.So my question is

Which callback method is needed for the above scenarios and Why?

Sandeep Sharma
  • 1,855
  • 3
  • 19
  • 34

1 Answers1

1

It would be good to place in onPause method as onDestroy is not guaranteed to be called always especially in your swipe-to-close case. And, onStop also not guaranteed to be called in low memory situation.

Official document about onDestroy also says as below;

Note: do not count on this method being called as a place for saving data!

Youngjae
  • 24,352
  • 18
  • 113
  • 198
  • But I do not want to free resources for example say when the user switches to another app.I only want to do that for the above mentioned cases.So how to handle above mentioned use cases with in the activity(say in pause method)? – Sandeep Sharma Jan 07 '16 at 05:05
  • For that, you could use Service and check app running. This is common approach in messengers. – Youngjae Jan 07 '16 at 05:13
  • May be I'm so silly. But if app is not showing on the foreground and it is in memory then how to get information for above mentioned user events(related to closing of app)? Do application have some state values for that or I need to think something else? – Sandeep Sharma Jan 07 '16 at 05:39
  • Simply send intent data (kind of `isRunning` Boolean value stored) in `onPause` and `onResume`. Communication between Activity and Service is out of this topic but this link might help: http://stackoverflow.com/q/20594936/361100 – Youngjae Jan 07 '16 at 05:44
  • I solved one use case(when user clicks back button) by http://stackoverflow.com/questions/9995490/how-to-set-onbackbutton-listener-to-an-activity and for another use case I can use Service and Activity communication as suggested but I have not tried.As I'm thinking right now ,the reasoning for that is because app is no more so I can use Service to find if app is running. Am I right? – Sandeep Sharma Jan 07 '16 at 06:20
  • @SandeepSharma // exactly right. And, it can help to re-establish server connection(or session) more quickly. – Youngjae Jan 07 '16 at 06:23