简体   繁体   中英

is it really wrong to release resources in onDestroy?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM