11

I have 2 activity, so activity 1 go to activity 2 then on activity 2 I have an exit button. But when I click it, all it only exited the activity number 2 and return to activity 1 again. Its basically felt like I just started the application again. I am not sure why?

This is my code.

Button btExit = (Button) findViewById(R.id.btExit);
    btExit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
            System.exit(0);
        }
    });
Lucifer
  • 29,392
  • 25
  • 90
  • 143
zBaoAnhLe
  • 253
  • 1
  • 6
  • 19

6 Answers6

7

Don't use System.exit.

If you want user to close app from any Activity I suggest using startActivityForResult, checking returned value in onActivityResult in first Activity and calling finish() there too.

MaciejGórski
  • 22,187
  • 7
  • 70
  • 94
  • 3
    Why? finish does not closes the application, only activity is closed. People, try to understand that we have many other classes that are not derived from Activity. They may be used to automate DB conection, store login id, user name, last query results... So closing activity does NOT SOLVE the problem in production environment. Aaa, cześć Maciek ;) – TomeeNS Oct 02 '15 at 02:44
4

You can either simulate hitting the home button:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

but this will not close the app..

to close it, you can do as https://stackoverflow.com/a/9735524/1434631

Community
  • 1
  • 1
Nermeen
  • 15,883
  • 5
  • 59
  • 72
  • 1
    Bringing up the HOME application won't change the current state of this task. That means, using this example, that when the user starts this application again from the HOME screen, it will bring the existing task (containing Activity1 and Activity2) back to the front and show the user Activity2 (which is probably not what OP wants to happen. The linked solution is better. – David Wasser May 10 '13 at 12:20
2

Use
finishAffinity(); to exit from the application .

finish() will only clears the activity from the activity stack.

krishnamurthy
  • 1,574
  • 14
  • 14
1

System.exit(0) does not work for closing application

  ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    am.killBackgroundProcesses("com.root.abc");
    
    System.runFinalizersOnExit(true);
    System.exit(0);


add Manifest permission
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
Community
  • 1
  • 1
Ashutosh Srivastava
  • 597
  • 1
  • 9
  • 13
0

use finish() and a sharedPreference flag and set the flag when you click button. on your other activity, check the flag and finish() it if the flag is set

Jithu
  • 1,478
  • 1
  • 13
  • 21
0

Finish the first activity by calling finish(); on the buttonclick after passing the intent to start the next activity.

ASP
  • 3,645
  • 1
  • 31
  • 45