How to finish Activity when starting other activity in Android?

mrh*_*nds 30 android android-activity

I have problems to finish the activity before. I want to start another activity and finish the current activity. When I used finish it didn't exit the current activity.

How can I exit the activity before?

Vik*_*tel 105

您需要首先使用intent当前context的其他活动startActivity.之后,你可以finish你目前activity从您重定向哪里.

 Intent intent = new Intent(this, FirstActivity.class);// New activity
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(intent);
 finish(); // Call once you redirect to another activity
Run Code Online (Sandbox Code Playgroud)

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) - 清除活动堆栈.如果您不想清除活动堆栈.然后,PLease不使用该标志.

  • 它确保您无法使用BACK按钮返回上一个活动. (6认同)
  • 如果 FLAG_ACTIVITY_CLEAR_TOP 清除堆栈,为什么我们需要 finish() (2认同)

Rau*_*ann 6

最好的——也是最简单的——解决方案可能是这样的:

Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finishAndRemoveTask();
Run Code Online (Sandbox Code Playgroud)

文档finishAndRemoveTask()

当您的活动完成并且应该关闭并且任务应该作为完成任务的根活动的一部分被完全删除时调用它。

这就是你要找的吗?


Rob*_*mar 5

Intent i = new Intent(this,Here is your first activity.Class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();
Run Code Online (Sandbox Code Playgroud)