60

根据super.onDestroy();析构函数中的哪个逻辑在顶部?例如:

protected void onDestroy() {        
    super.onDestroy();
    releaseMediaPlayer();
}

并不是:

protected void onDestroy() {        
    releaseMediaPlayer();
    super.onDestroy();
}

就像在 c++、obj-c、pascal 等中一样?

4

4 回答 4

68

这真的取决于你想在你的onDestroy. 这就是 super.onDestroy 所做的(按此顺序):

  • 关闭活动正在管理的任何对话框。
  • 关闭活动正在管理的所有游标。
  • 关闭任何打开的搜索对话框

如果你放在里面的逻辑onDestroy和android做的那三件事有关,那么你可能不得不担心顺序。否则,在大多数情况下,这并不重要。

于 2010-12-12T20:01:03.897 回答
13

报告工作状态培训的 ThreadSample.zip中,onDestroy() 中有注释

public void onDestroy() {
    ...
    // Must always call the super method at the end.
    super.onDestroy();
}

所以也许在使用广播接收器时,超级必须在最后。

于 2014-05-26T23:05:49.677 回答
10

Since we are extending from the base android classes, it is always good approach to let the parent class create and initialize itself first during the creation and let the child uninitialize and free the resource first during shutdown/stopping the components. This is the recommended approach to be followed. however, it entirely depends on the use cases and scenarios.

public void onCreate(Bundle bundle){
   super.onCreate(bundle);
   //perform child class initializations.
}

public void onDestroy(){
   //perform uninitialization and free resource
    super.onDestroy();
}
于 2016-02-25T14:50:42.840 回答
5

你有什么问题?您可以采用任何一种方式,这取决于您是否希望在您的超类onDestroy()之前调用​​您的超类。通常我认为这在android中并不重要。

另外, onDestroy()不是析构函数。它实际上并没有破坏对象。它只是一种基于某种状态调用的方法。onDestroy()因此,在超类运行并返回之后,您的实例仍然存在并且非常好* 。

*最有可能的是,android 可以随时终止该活动,但您可以假设它仍然存在。

于 2010-12-12T19:58:12.277 回答