In which cases should one override onDestroy()?
I'm reading up on the activity lifecycle, and reading the documentation on starting and destroying activities, at the follow link: http://developer.android.com/training/basics/activity-lifecycle/starting.html
The following text is from the link:
Destroy the Activity
While the activity's first lifecycle callback is onCreate(), its very last callback is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory.
Most apps don't need to implement this method because local class references are destroyed with the activity and your activity should perform most cleanup during onPause() and onStop(). However, if your activity includes background threads that you created during onCreate() or other long-running resources that could potentially leak memory if not properly closed, you should kill them during onDestroy().
Can someone give an example(or examples) of background threads or "other long-running resources" that would warrant an onDestroy() override, and explain how they avoid the regular onDestroy() cleanup?
Clarification: I understand how onPause(), onStop() and onDestroy() work, that's not what I'm asking about. I'm asking for a more in-depth clarification of what would warrant overriding onDestroy()
Well, onDestroy() is a method called by the framework when your activity is closing down. It is called to allow your activity to do any shut-down operations it may wish to do. The method doesn't really have anything to do with garbage collection. In particular, it has nothing to do with C++ destuctors (despite its name).
This method gives your program a chance to do things like cleanup resources, so that they don't pollute the associated application. If you have no shut-down operations to do, you don't need to override it. The base class does essentially nothing.
You have to put cleanUp logic
in onDestroy()
when you can't put it in onPause()
or onStop()
.
Example : You want your activity to do something only when it is finishing ie, only once. You can't put that logic in onStop()
because it is called whenever your activity loses focus
or in onPause()
- called whenever your activity goes to background
.
上一篇: 如何在App启动时停止服务