Finish all activities at a time

2019-01-02 15:35发布

I have an application with multiple pages i.e., multiple activities and some of them remain open.

Is there a way to close all activities at once?

17条回答
唯独是你
2楼-- · 2019-01-02 15:46

The best solution i have found, which is compatible with devices having API level <11

Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);

This solution requires Android support library

查看更多
一个人的天荒地老
3楼-- · 2019-01-02 15:46

Following two flags worked for me. They will clear all the previous activities and start a new one

  Intent intent = new Intent(getApplicationContext(), MyDetails.class);
  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);

Hope this helps.

查看更多
牵手、夕阳
4楼-- · 2019-01-02 15:47

Whenever you wish to exit all open activities, you should press a button which loads the first Activity that runs when your application starts then clear all the other activities, then have the last remaining activity finish. to do so apply the following code in ur project

Intent intent = new Intent(getApplicationContext(), FirstActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code finishes all the activities except for FirstActivity. Then we need to finish the FirstActivity's Enter the below code in Firstactivity's oncreate

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

and you are done....

查看更多
还给你的自由
5楼-- · 2019-01-02 15:51

For API 16+, use

finishAffinity();

For lower, use

ActivityCompat.finishAffinity(YourActivity.this)
查看更多
美炸的是我
6楼-- · 2019-01-02 15:58

If rooted:

Runtime.getRuntime().exec("su -c service call activity 42 s16 com.example.your_app");
查看更多
柔情千种
7楼-- · 2019-01-02 15:59

I was struggling with the same problem. Opening the about page and calling finish(); from there wasn't closing the app instead was going to previous activity and I wanted to close the app from the about page itself.

This is the code which worked for me:

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

Hope this helps.

查看更多
登录 后发表回答