Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it really wrong to release resources in onDestroy?

Tags:

android

Android documentation says (in http://developer.android.com/training/basics/activity-lifecycle/stopping.html):

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.

Sounds like it is wrong. How could killed process leak memory?

like image 960
user983447 Avatar asked Feb 19 '23 02:02

user983447


1 Answers

Suppose you started a service in your onStart() method, and you intend to stop that service when the user gets out of the Activity.

If you put the code to stop the service in onDestroy(), that code may never get called, which can leave that service running until Android decides to kill it (which may not happen for a while, if ever). That running service is and example of leaking memory/resources outside your application.

You should put cleanup code like that in a method that is guaranteed to be called.

Note that a process is killable after onPause() has been called, so onPause() is really the place you want to do cleanup that absolutely must happen.

(See table 1 in https://developer.android.com/guide/components/activities.html for details on the Activity lifecycle)

Another thing that might be really bad to leak: Bluetooth discovery or location reporting (GPS or network-based) turned on but not off as soon as possible - very bad for battery life.

like image 54
Scott Stanchfield Avatar answered Mar 05 '23 04:03

Scott Stanchfield