10

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?

Community
  • 1
  • 1
user971511
  • 167
  • 1
  • 2
  • 7
  • 1
    I wouldn't recommend that because the user has the option to press the home button to do that (android will kill your app anyway if it needs memory). Because of such decisions the users start to use task killer which are a mess (in my opinion). Then the developers are trying hard to make their applications to work because the user is killing his application by a task killer... Don't mess with the android lifecycle ;-) – Knickedi Oct 06 '11 at 14:46
  • Why would you even want to do this though? I. Can't think of a single benefit. – frostymarvelous Apr 01 '15 at 19:22
  • One benefit is that if activity layout is complex and takes e.g. 10 seconds to be loaded then one can save that 10 second with reuse the activity without creating it from scratch. – Dr. Ehsan Ali Jul 25 '15 at 09:42

2 Answers2

17

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.

Emir Kuljanin
  • 3,881
  • 1
  • 25
  • 30
  • 2
    I found this answer useful, but a note of warning to unsuspecting developers: When you need a Context, **please don't use the Application Context** unless you know what you're doing. In this case, you can simply pass `this` (the current Activity instance) instead of the Application Context. – Vicky Chijwani May 27 '16 at 12:19
0

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

public void onBackPressed () 
{
    moveTaskToBack (true);
}
Setsuki
  • 255
  • 2
  • 11