在不使用onpause()或onstop()的情况下调用ondestroy()的Android场景
问题描述:
几天前,我被要求写下在不调用onpause()或onstop()的情况下调用ondestroy()的方案.是否有可能.如果是,请解释.
A few days back I was asked to write down scenarios where ondestroy() is called without onpause() or onstop() being called. Is it possible. If yes please explain.
答
如果尝试下面的代码,您会发现在onPause()
和onStop()
生命周期回调被跳过的情况下,确实调用了onDestroy()
的情况./p>
If you try below code, you will find a scenario where onDestroy()
is indeed getting called while onPause()
and onStop()
lifecycle callbacks are skipped.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
finish();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("MainActivity", "onDestroy");
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.e("MainActivity", "onPause");
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("MainActivity", "onStop");
}
换句话说,如果在onCreate()
中创建活动时调用finish()
,则系统将直接调用onDestroy()
.
In other words, if you call finish()
while creating the Activity in onCreate()
, the system will invoke onDestroy()
directly.