Override back button to act like home button
Most of the time you need to create a Service to perform something in the background, and your visible Activity
simply controls this Service
. (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 your Activity
can finish
as usual and the Service
will still be running.
A simpler approach is to capture the Back
button press and call moveTaskToBack(true) as follows:
// 2.0 and above
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
// Before 2.0
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
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.
Use the following code:
public void onBackPressed() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.
However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service
. The documentation says the following about Services:
A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.
These seems appropriate for your requirements.