Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go back to Activity without recreating (without invoking onCreate())

I would like to ask similar question to:

Go back to previous screen without creating new instance

However I don't want Activity A go through onCreate callback, I would like to return to previous instance in the same state. How to achieve that without calling multiple finish() ?

like image 251
Adam Styrc Avatar asked Apr 13 '16 13:04

Adam Styrc


1 Answers

There's no need to finish() activities as you navigate through your application. Instead, you can maintain your Activity back-stack and still achieve your goal. Let's say you have 4 activites like so:

A --> B --> C -->D

where D is the topmost activity and A is root activity. If you are 'falling back' to activity B, then you'll need to do two things in order to avoid hitting B's onCreate method.

1.) Make B a "SingleTask" activity. You can do this in the Android Manifest. To be brief, this means that only one 'instance' of B will ever exist within this Task. If B is already running when it's called then it will simply be brought to the front. This is how you do that.

  <activity
        android:name=".ui.MyActivity"
        android:launchMode="singleTask"/>

But you don't want to just bring B to the front. You want to 'fall back' to B so that your stack looks like

A--> B

2.) Add this flag to your intent that 'starts' B. This ensures that C and D are removed.

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Now when 'D' calls new Intent to B, B will be resumed and C and D will be removed. B will not be recreated, it will only call onNewIntent.

like image 185
Caleb Avatar answered Sep 18 '22 15:09

Caleb