user971511
user971511

Reputation: 167

How to reuse Activities? Not to create activity each time

This topic is continue of this: Android. How to start activity without creating new one?

I have read that activities are destroyed when to click BACK button. They can be not destroyed when to move deeper to stack and then call activities back. using android:launchMode="singleTask" for example

is it possible that activities to not be destroyed when I click button BACK and then run activity again?

Upvotes: 10

Views: 13240

Answers (2)

Emir Kuljanin
Emir Kuljanin

Reputation: 3911

The default implementation of the back button is the finish the current activity. You may however intercept that key press and do whatever you wish with it. For instance, instead of finishing your current activity, you could "bring up" the previous activity and thus making it seem as if the normal implementation is at hand.

To intercept the back button press: Android: intercepting back key

And to start your previous activity without creating a new one every time:

Intent i = new Intent(this, PreviousActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);

In Kotlin 1.2:

val intent = Intent(this, RepairListActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
startActivity(intent)

Good luck.

Upvotes: 17

Setsuki
Setsuki

Reputation: 255

You can redefine the "onBack" method of your activity, something like

public void onBackPressed () 
{
    moveTaskToBack (true);
}

Upvotes: 0

Related Questions