I did a simple sample with 3 activities:
ActivityA
ActivityB
ActivityC
There is just one button on each of them.
Button on ActivityA
opens ActivityB
val intent = Intent(this, ActivityB::class.java)
startActivity(intent)
Button on ActivityB
opens ActivityC
val intent = Intent(this, ActivityC::class.java)
startActivity(intent)
Button on ActivityC
is supposed to go back to ActivityA
but killing of ActivityB in the process
val intent = Intent(this, ActivityA::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
startActivity(intent)
It does what I want and the whole flow looks like this when logged:
ActivityA onCreate()
ActivityA button clicked
ActivityB onCreate()
ActivityB button clicked
ActivityC onCreate()
ActivityC button clicked
ActivityB onDestroy()
ActivityA onDestroy()
ActivityA onCreate()
ActivityC onDestroy()
The problem with this solution is the fact that ActivityA
gets recreated (destroy and create). Is there a way to just resume it instead?
Disclaimer:
This is, of course just a simplified case. Because of the several reasons in my app I'd rather avoid using onActivityResult()
and finish()
on click approaches. I need to preserve proper back button behaviour.
You're doing it almost right. What you're missing (to avoid activity recreate) is a FLAG_ACTIVITY_SINGLE_TOP
flag.
val intent = Intent(this, ActivityA::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
More about it here