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

Hemant Parmar picture Hemant Parmar · Dec 20, 2014 · Viewed 15.6k times · Source

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.

Answer

AADProgramming picture AADProgramming · Dec 26, 2014

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.