M.A*_*han 4 android activity-lifecycle ondestroy onpause android-activity
我对super()覆盖函数中的函数调用感到困惑.
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
Run Code Online (Sandbox Code Playgroud)
是的代码的影响,之前或之后写什么super.onDestroy() 或
super.onPause()或其他超级功能在所有类型的android系统中被覆盖的方法呢?
在一般情况下,这是很好的做法,让基类初始化第一和销毁最后 -这样,从一个派生类取决于基类的任何初始状态将被先整理出来,相反,任何派生类清理代码可以依靠基类数据仍然有效.
在Android中,我将此行为扩展到onPause和onResume:
@Override
protected void onCreate(Bundle savedInstanceState) {
// let Android initialise its stuff first
super.onCreate();
// now create my stuff now that I know any data I might
// need from the base class must have been set up
createMyStuff();
}
@Override
protected void onDestroy() {
// destroy my stuff first, in case any destroying functionality
// relies upon base class data
destroyMyStuff();
// once we let the base class destroy, we can no longer rely
// on any of its data or state
super.onDestroy();
}
@Override
protected void onPause() {
// do my on pause stuff first...
pauseMyStuff()
// and then tell the rest of the Activity to pause...
super.onPause();
}
@Override
protected void onResume() {
// let the Activity resume...
super.onResume();
// and then finish off resuming my stuff last...
resumeMyStuff();
}
Run Code Online (Sandbox Code Playgroud)
实际上,onPause()并且onResume()并没有真正受到订单的影响,因为它们对活动的状态影响很小.但确保创建和销毁遵循base-create-first,base-destroy-last顺序非常重要.
但是,规则的例外总是存在,并且常见的是,如果要在onCreate()方法中以编程方式更改活动的主题,则必须在调用之前执行此操作super.onCreate().