Search code examples
androidandroid-activityandroid-lifecycle

Android scenario where ondestroy() is called without onpause() or onstop()


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.


Solution

  • 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.