Home > Blockchain >  How to close all previous Android actvitities except the first one?
How to close all previous Android actvitities except the first one?

Time:10-27

Consider a hypothetical e-banking app which the following flow:

HomeActivity -> CurrencyConverterActivity -> PickContactActivity -> InputDataTransferActivity -> TransferReviewActivity -> TransferConfirmationActivity

All activities (except HomeActivity) are invoked with the usual startActivity() and without finish(). This is intentional, so user can review the inputs on previous screen. But once you reach TransferConfirmationActivity and press back, I want to go back to HomeActivity (and the other activities are killed).

How to do this?

CodePudding user response:

I think you can use Intent.FLAG_ACTIVITY_CLEAR_TOP flag to achieve that.

According to Android Documentation about FLAG_ACTIVITY_CLEAR_TOP

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

val intent = Intent(this, HomeActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)

CodePudding user response:

start HomeActivity and add flag in intent

Intent intent = new Intent(activity, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
  • Related