在API 21上可以使用finishAndRemoveTask()

我会终止我的应用程序并从最近的任务列表中取消它。

finishAndRemoveTask()仅在API 21上可用。

我应该在低于21的API上使用什么?

对堆栈中的第一个活动进行意图并完成当前活动:

 Intent intent = new Intent(this, FirstActivity.class); intent.putExtra(EXTRA_FINISH, true); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); 

并且,在FirstActivityonResume方法中,类似于完成堆栈中的最后一个活动(并希望从最近的应用程序列表中删除应用程序):

 if (getExtras() != null && getIntentExtra(EXTRA_FINISH, false)) { finish(); } 

我有一个类似的用例,我需要完成所有活动。 这是一种没有finishAndRemoveTask()的方法。

使所有活动扩展为基类,其中包含以下内容:

 private Boolean mHasParent = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { mHasParent = extras.getBoolean("hasParent", false); } } // Always start next activity by calling this. protected void startNextActivity(Intent intent) { intent.putExtra("hasParent", true); startActivityForResult(intent, 199); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 199 && resultCode == FINISH_ALL) { finishAllActivities(); } } protected void finishAllActivities() { if (mHasParent) { // Return to parent activity. setResult(FINISH_ALL); } else { // This is the only activity remaining on the stack. // If you need to actually return some result, do it here. Intent resultValue = new Intent(); resultValue.putExtra(...); setResult(RESULT_OK, resultValue); } finish(); } 

只需在任何活动中调用finishAllActivities() ,所有活动都将展开。 当然,如果您不关心最后一个活动返回的结果,那么代码可以变得更加简单。