On pressing the back button, I'd like my application to go into the stopped state, rather than the destroyed state.
In the Android docs it states:
...not all activities have the behavior that they are destroyed when BACK is pressed. When the user starts playing music in the Music application and then presses BACK, the application overrides the normal back behavior, preventing the player activity from being destroyed, and continues playing music, even though its activity is no longer visible
How do I replicate this functionality in my own application?
I think there must be three possibilities...
Capture the back button press (as below) and then call whatever method(s) the home button calls.
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { Log.d(this.getClass().getName(), "back button pressed"); } return super.onKeyDown(keyCode, event); }
Capture the back button press and then spoof a home button press.
Capture the back button press, then start an Activity of the home screen, effectively putting my application's Activity into the stopped state.
Edit: I know about services and am using one in the application to which this problem is related. This question is specifically about putting the Activity into the stopped state rather than the destroyed state on pressing the back button.
Most of the time you need to create a Service to perform something in the background, and your visible
Activity
simply controls thisService
. (I'm sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that's the case, then yourActivity
canfinish
as usual and theService
will still be running.A simpler approach is to capture the
Back
button press and call moveTaskToBack(true) as follows:I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But
moveTaskToBack
can be used as a quick alternative on occasion.NOTE: as pointed out by Dave below Android 2.0 introduced a new
onBackPressed
method, and these recommendations on how to handle the Back button.Override onBackPressed() after android 2.0. Such as
Working example..
Make sure don't call super.onBackPressed();
In this way your Back Button act like Home button . It doesn't finishes your activity but take it to background
Second way is to call
moveTaskToBack(true);
inonBackPressed
and be sure to removesuper.onBackPressed
if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works
hope it helps someone, cheers
Use the following code:
I have use @Mirko N. answser using made the new Custom EditText
Then set data from your activity
Thank you.