17

Right now an activity gets destroyed when the BACK key is pressed. How can I make it just stop ( i.e. keep all the variables, etc. alive ), rather then be destroyed?

Thanks!

Roger
  • 6,443
  • 20
  • 61
  • 88
  • http://stackoverflow.com/questions/3141996/android-how-to-override-the-back-button-so-it-doesnt-finish-my-activity – MD Sayem Ahmed Jul 22 '11 at 14:30
  • similar, but it runs the main activity when the back key is presses. I need just to stop ( i.e. pause and move to background, therefor returning to previous activity ). – Roger Jul 22 '11 at 14:49
  • What/how many variables? How are they being used? You might consider setting them up as class variables instead of worrying about keeping that activity alive. – Rob Jul 22 '11 at 15:16
  • see my answer here.. http://stackoverflow.com/questions/5914040/onbackpressed-to-hide-not-destroy-activity/23759328#23759328 – Zar E Ahmer May 20 '14 at 12:05

7 Answers7

14

Why is it that you need to keep the variables alive? Given the established lifecycle of an Android application, I'm not sure that preventing the activity from being destroyed "just to keep the variables" makes sense.

  1. Even if you stop the application without destroying it, there is always the chance that Android will kill it to free up memory. You will have to account for this in your code anyway, and so preventing the application from destroying doesn't save you from writing code.

  2. Variables can be saved and restored relatively easily and quickly using SharedPreferences in your onPause() and onResume() methods. Unless you are storing a ton of data, preventing the application from destroying might not make much of a difference.

  3. It sounds like you want to keep the variables in memory because you intend to return to this activity. Typically, you don't use the back button to navigate away from activities that you intend to come back to. Instead you would create an Intent and start a new activity. When you do this, Android places the current activity on the Back Stack calling onPause() and onStop(), which seems like exactly the sort of behavior you are looking for.

So if you still really want to prevent your activity from being destroyed (at least until Android decides it's using too much memory and kills it on it's own) you could always use Sagar's code and start a new activity in onBackPressed().

@Override
public void onBackPressed()
{
    Intent intent = new Intent(this, Other.class);
    startActivity(intent);       
}

Just be certain that that is what you really want to do.

theisenp
  • 8,639
  • 5
  • 39
  • 47
  • Thanks, works... just one detail, how should I make it know which activity had started this activity, so that it would know to which to return? – Roger Jul 22 '11 at 15:41
  • 1
    If you just want to return to the previous activity, then why is the back button's normal functionality not acceptable? You could determine the first activity by including information about it in the Intent that you used to start the second activity with intent.putExtra("activity_name", "activity_1") and then retrieving that name in the second activity. But unless you are doing something very unusual in your activity, your interests would be better served by saving your data properly in onPause() and onResume() without overriding onBackPressed(). – theisenp Jul 22 '11 at 15:53
  • One reason you would want the backkey to act like the home key if for a timer app. – Andi Jay Jun 04 '12 at 03:40
  • 1
    Placing the logic for a timer app inside of an Activity (and overriding the functionality of the back button) is almost certainly incorrect. Long running tasks like playing music or setting a timer should happen in a Service, where they will be outside of the Activity life cycle. – theisenp Jun 04 '12 at 21:12
13

Simple one line

@Override
public void onBackPressed() {
    mActivity.moveTaskToBack(true);
}
Atif Mahmood
  • 8,882
  • 2
  • 41
  • 44
7

Pressing the BACK key triggers the onBackPressed callback method of Activity class. The default implementation of this callback calls the finish() method.

http://developer.android.com/reference/android/app/Activity.html#onBackPressed()

You can override this method to move the activity to background (mimick the action of pressing the HOME key.

eg:


@Override
public void onBackPressed() {
    onKeyDown(KeyEvent.KEYCODE_HOME);        
}

You could also instead consider moveTaskToBackground() mentioned here:

Override back button to act like home button

Community
  • 1
  • 1
Sagar Hatekar
  • 8,700
  • 14
  • 56
  • 72
  • no, no, just need to stop one activity, not the whole application. :) – Roger Jul 22 '11 at 14:42
  • I believe if you stop an Activity, you'd lose it's Context and all it's local variables. This defends the purpose of what you're trying to achieve. Correct me if I am wrong. – Sagar Hatekar Jul 22 '11 at 14:51
  • not really, if I Override back button to act like home button, the content is still there, when I launch the application again. The problem is that it stops the whole app, while I just need to stop one activity. :) – Roger Jul 22 '11 at 14:58
2

I have managed to work out exactly what you want: switch between 2 activities using Back button and keep them all not to be destroyed!

For example: you have 2 activities A & B. A will be started first, then A calls B. When B is loaded, user press Back button and switches back to activity A from B. From now B should not be destroyed and just goes to background, and when user starts activity B from A again, activity B will be brought to foreground, instead of being re-created again or created new instance!

How to implement this:

1. Override onBackPressed() of activity B:

@Override
public void onBackPressed() {
    Intent backIntent = new Intent(this, ActivityA.class);
    backIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(backIntent);
}

2. On activity A, call activity B:

public void callActivityB() {
    Intent toBintent = new Intent(this, ActivityB.class);
    toBIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(toBintent);
}

remember to add flag: Intent.FLAG_ACTIVITY_REORDER_TO_FRONT when you call A&B.

Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
Hoang Nguyen Huu
  • 1,202
  • 17
  • 17
  • 1
    Thanks for this idea. At least it's closer to the real answer to what was asked, not all those suggestions "why do you need this". Though maybe it needs more adjustments as in my case if you go back from B to A and then press back again it gives an exception stack trace and show activity B again. Maybe should find another Intent flag that could help. – mortalis Sep 28 '18 at 19:12
1

This is similar to this question that was asked earlier.

Hope this helps! N.S.

Community
  • 1
  • 1
Jonathan Pitre
  • 2,355
  • 3
  • 22
  • 38
  • 4
    close, but "moveTaskToBack(true);" stops the whole application ( i.e. acts as a "home" button ), while I just need to stop one activity. – Roger Jul 22 '11 at 14:40
0

First of all, sorry for not answering the question, cause, I still have no optimal answer for it. But, I really like when people start asking "what do you need this for". And, very rarely, the person who asked the question, really deserves this kind of question. I think not this time, but ok, this is not the issue...

Anyway, I will try to point out why some of us are convinced that

going from Activity A to Activity B(creating UI based on some data fetching) AND

going back from B to A(destroying all the created UI and/or fetched data in B) is sometimes a bad concept. Better solution would be to keep the stack as it is, so using something like finish() in Activity B, but keeping the Activity B in Pause state, so later when calling it again from Activity A - it just goes in onResume = nothing recreated in UI, no additional data fetching. The bonus of course is a fast and responsive UI, and the difference is really if you have a more complicated UI layout.

miroslavign
  • 2,033
  • 2
  • 24
  • 26
-4

Just specify in the manifest for the activity as

 android:persistent="true"

That should prevent your activity getting destroyed. To know more about this please refer to these below links which were answered by me

How to prevent call of onDestroy() after onPause()?

Prevent activity from being destroyed as long as possible

In the above posts I have explained in detail with a use case

Community
  • 1
  • 1
Aravind.HU
  • 9,194
  • 5
  • 38
  • 50
  • 1
    This attribute does not exist for activities: https://developer.android.com/guide/topics/manifest/activity-element.html – jekatt Aug 20 '16 at 14:16
  • @jekatt it does exists https://developer.android.com/guide/topics/manifest/application-element.html – Aravind.HU Aug 22 '16 at 00:24
  • @aravind.udayashankara this attribute is for `` as was described in documentation you referred. Also in this documentation https://developer.android.com/guide/topics/manifest/activity-element.html about `` the `android:persistent` attribute not exists – Sayed Abolfazl Fatemi Dec 05 '16 at 09:50