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

末鹿安然 提交于 2019-12-03 11:06:04

问题


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.


回答1:


If you try below code, you will find a scenario where onDestroy() is indeed getting called while onPause() and onStop() Life-cycle call backs 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");

    }

Hence, if you call finish(), once Activity is created, system will invoke onDestroy() directly.




回答2:


This happens when we call finish method to activity Example: inside your activity call this.finish();




回答3:


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




回答4:


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:

  1. Dismiss any dialogs the activity was managing.
  2. Close any cursors the activity was managing.
  3. Close any open search dialog


来源:https://stackoverflow.com/questions/27578708/android-scenario-where-ondestroy-is-called-without-onpause-or-onstop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!