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

2019-01-04 12:03发布

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);
        }
    });

6条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-04 12:35

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

查看更多
放荡不羁爱自由
3楼-- · 2019-01-04 12:43

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

查看更多
相关推荐>>
4楼-- · 2019-01-04 12:43

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

查看更多
欢心
5楼-- · 2019-01-04 12:45
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.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-04 12:47

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.

查看更多
老娘就宠你
7楼-- · 2019-01-04 12:48

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" />
查看更多
登录 后发表回答