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.
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");
}
In other words, if you call finish()
while creating the Activity in onCreate()
, the system will invoke onDestroy()
directly.
This happens when we call finish method to activity
Example:
inside your activity call this.finish();
onPause() and onStop() will not be invoked if finish() is called from within the onCreate() method. This might occur, for example, if you detect an error during onCreate() and call finish() as a result. In such a case, though, any cleanup you expected to be done in onPause() and onStop() will not be executed.
Although onDestroy() is the last callback in the lifecycle of an activity, it is worth mentioning that this callback may not always be called and should not be relied upon to destroy resources. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.It is better have the resources created in onStart() and onResume(), and have them destroyed in onStop() and onPause, respectively.
Refrence - https://www.toptal.com/android/interview-questions
This is possible when we call finish() directly in an activity. When finish() is called in an activity, onDestroy() is executed and it does following things: