Override the Back Button to Mimic the Home Button's Behavior
Proceeding from the traditional behavior of ending an activity's existence upon pressing the back button, you seek an alternative approach that places it in a stopped state instead.
As alluded to in the Android documentation, this is observed in the Music application, where accessing music and subsequently hitting the back button allows playback to continue despite the player activity being out of sight.
To replicate this, several approaches are considered:
Preferred Solution:
A simpler approach is to intercept the Back button press and invoke the moveTaskToBack(true) method:
// For Android 2.0 and above @Override public void onBackPressed() { moveTaskToBack(true); } // For pre-Android 2.0 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); return true; } return super.onKeyDown(keyCode, event); }
While the preferred approach is to allow the activity to complete normally and restore its state from a service, moveTaskToBack offers a quick workaround.
Caution:
Note that Android 2.0 introduced the onBackPressed method, which provides alternative guidelines for handling the Back button.
The above is the detailed content of How Can I Override the Back Button to Behave Like the Home Button in Android?. For more information, please follow other related articles on the PHP Chinese website!