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.
There is another scenerio where onPause is called once before onStop(), and in a worker thread that is not stopped, finish() is called which would skip onPause() and get onDestroy() to be called.
Answer: 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.
onDestroy() before calling your code. super. onDestroy() should be called at the end because then your code will be called before it is destroyed.
onPause() is always called. This is guaranteed. If you need to save any state in your activity you need to save it in onPause() . onStop() may be called after onPause() , or it may not.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With