I can not finish the Activity

Viewed 116

My problem is this ... I have 3 Activities:

(ActivityA), (ActivityB) and (ActivityC)

From ActivityA to ActivityB I use the following code:

val intent = Intent(this, ActivityB::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
startActivity(intent)
finish()

From ActivityB to ActivityC I also use this code:

val intent = Intent(this, ActivityC::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
startActivity(intent)
finish()

But if I give onBackPressed or go to any other App and return to my App, instead of returning to ActivityC, it goes to ActivityA.

4 Answers

Use this instead

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
finish()

You'll need to remove Intent.FLAG_ACTIVITY_NO_HISTORY from the Intent for starting Activity C, as the flag prevents the new activity from being added to the back stack and finishes the activity when it is navigated away from. This means your app will start with it's launcher activity, which I assume is Activity A. You can read more about this flag here in the documentation.

From Activity A to Activity B do like this -

val intent = Intent(this, ActivityB::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()

And from Activity B to Activity C do like this -

val intent = Intent(this, ActivityC::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()

You have to remove intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY).

It does clear the history of current activity.

Related