Stranger B.
Stranger B.

Reputation: 9364

How to go back to an already launched activity in android

I want to go back to an already launched activity without recreating again.

  @Override
    public void onBackPressed() {
     Intent i = new Intent(SecondActivity.this, FirstActivity.class);
     this.startActivity(i);

    }

Instead of doing is there any other way to go back to another activity which is already created, which I get back with " Back button "

Upvotes: 0

Views: 83

Answers (5)

Hemanth
Hemanth

Reputation: 2737

Don't call finish() on 1st Activity, when you start 2nd Activity. When back is pressed on 2nd Activity, it finishes itself and goes back to 1st Activity by default. onCreate() is not called for 1st Activity in this case. No need to override onBackPressed() in 2nd Activity.

However, Android can destroy 1st Activity when you are using 2nd Activity, to reclaim resources, or, if you have checked Don't keep activities in Developer options. In such case you can use onSaveInstanceState() to save data and onRestoreInstanceState() to use it again in 1st Activity. You can also get the saved data in onCreate(). Here is how it works. Also, onSaveInstanceState() is called only if android decides to kill the Activity and not when user kills the Activity(e.g. using back button).

Upvotes: 0

Jorge Casariego
Jorge Casariego

Reputation: 22212

Whenever you start a new activity with an intent you can specify an intent flag like this:

// this flag will cause the launched activity to be brought to the front 
// of its task's history stack if it is already running.
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

or

// If set and this intent is being used to launch a new activity from an
// existing one, the current activity will not be counted as the top activity
// for deciding whether the new intent should be delivered to the top instead
// of starting a new one.
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);

Upvotes: 1

David Heisnam
David Heisnam

Reputation: 2491

Add android:launchMode="singleTop" in the FirstActivity declaration in your AndroidManifest.xml like so

<activity
        android:name=".FirstActivity"
        android:launchMode="singleTop"/>

You could also try the following if SecondActivity was started from FirstActivity

@Override
public void onBackPressed() {
     this.finish();
}

Upvotes: 1

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

On your second Activity, close the Activity calling finish() instead of creating a Intent for the other screen.

By calling finish() the Application will go back in the Activity stack and show the previous Activity (if its not finished()).

Upvotes: 0

Aakash
Aakash

Reputation: 5261

When starting SecondActivity do not finish the first activity so when you go back , you will be taken to the first activity.

Intent i = new Intent(FirstActivity.this,SecondActivity.class);
startActivity(i);

Upvotes: 0

Related Questions