0

I am trying to call onPause(), onStop(), onDestroy from a specific button to exit the application (this is my assignment details). This is the code I've written:

Button exitBtn = (Button) findViewById(R.id.exitBtn);
    exitBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Button Exit clicked
            // going through the LifeCycle

            MainActivity.super.onPause();
            MainActivity.super.onStop();
            MainActivity.super.onDestroy();
        }
    });

But when I click the button in the application it stops suddenly and displays the message: "App has stopped". It shouldn't crash it should just exit the application

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Obi
  • 89
  • 8
  • 4
    Possible duplicate of [How to force stop my android application programmatically?](https://stackoverflow.com/questions/5100728/how-to-force-stop-my-android-application-programmatically) – azro Mar 25 '18 at 09:58
  • 2
    These methods are called by Android system on its own. You should have no reason to call them at all. This, I feel, is an example of XY problem. – M. Prokhorov Mar 25 '18 at 10:33
  • You can simply use `finish()` method to close an Activity. Why don't you use that method? – Rahulrr2602 Mar 25 '18 at 12:18

1 Answers1

1

Call finish() on MainAcitivty instead of directly calling those methods. Or another bad way of doing it would be executing the following:

System.exit(0)

As someone mentioned in the comment above, onPause(), onStop(), and onDestroy() are called by Android system itself. Check this out for more understanding about Activity lifecycles.

Fatmajk
  • 1,770
  • 1
  • 13
  • 22
  • Like I said the tutor specificaly asked not to use System.exit(0) and to do it with the onPause(), onStop, and onDestroy(). I don't know why and he didn't explain how to do it/. – Obi Mar 25 '18 at 10:49
  • @ObadaA.Ahmar, while it always remains a possibility that your tutor is wrong, I really doubt that this is the case. And, since he is a tutor, he **absolutely should** explain what he means and why you should do what you should. So go and ask him. – M. Prokhorov Mar 25 '18 at 11:52