Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.exit(0) doesnt close all my activities?

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);
        }
    });
like image 228
zBaoAnhLe Avatar asked May 10 '13 11:05

zBaoAnhLe


1 Answers

System.exit(0);

is a bad way of termination of android apps. Android manages it in its own os

You can bring up the Home application by its corresponding Intent:

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

hope this helps

EDIT :-

Then I suppose you are aiming at finishing all the stacked up activity..

Here it is :-

Closing all the previous activities as follows:

Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("Exit me", true);
startActivity(intent);
finish();

Then in MainActivity onCreate() method add this to finish the MainActivity

if( getIntent().getBooleanExtra("Exit me", false)){
    finish();
}

The result will be same as above, but because all your stacked up activities are closed, when you come back to you app it must start from your main activity i.e launcher activity.

Hope this helps.

like image 191
CRUSADER Avatar answered Oct 03 '22 13:10

CRUSADER