我会终止我的应用并将其从最近任务列表中取消。
finishAndRemoveTask()
只适用于 API 21 及以上版本。
在低于 API 21 的版本中,我应该使用什么?
我会终止我的应用并将其从最近任务列表中取消。
finishAndRemoveTask()
只适用于 API 21 及以上版本。
在低于 API 21 的版本中,我应该使用什么?
将意图设置为栈中第一个活动并结束当前活动:
Intent intent = new Intent(this, FirstActivity.class);
intent.putExtra(EXTRA_FINISH, true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
在FirstActivity
的onResume
方法中,可以使用以下代码完成堆栈中的最后一个活动(并希望将应用程序从最近的应用程序列表中删除):
if (getExtras() != null && getIntentExtra(EXTRA_FINISH, false)) {
finish();
}
FirstActivity
是堆栈中唯一的活动,并且它是该任务中该活动的唯一实例,并且不会从最近的任务中删除该任务。换句话说,这没有与finishAndRemoveTask
相似的效果。 - Alex.FfinishAndRemoveTask
类似的效果,当然不是完全相同的(并且,正如您所看到的,没有其他建议,因此现在这是最好的方法)。您的分析其余部分是错误的:许多活动可以在堆栈中,甚至可以有许多实例,这要归功于FLAG_ACTIVITY_CLEAR_TOP标志。无论如何,最重要的是:这只是旧设备的解决方法。 - thelawnmowermanprivate 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()
,所有活动都将被解除。当然,如果您不关心最后一个活动返回的结果,代码可以变得更简单。