0

Is it possible to change this code:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

    }
    return super.onKeyDown(keyCode, event);
}

so that when I click on back button it works like a home button?

Dennis Meng
  • 5,002
  • 14
  • 31
  • 36
user1302569
  • 6,941
  • 13
  • 45
  • 65
  • possible duplicate of [Android - How To Override the "Back" button so it doesn't Finish() my Activity?](http://stackoverflow.com/questions/3141996/android-how-to-override-the-back-button-so-it-doesnt-finish-my-activity) – K_Anas Jun 28 '12 at 08:02

4 Answers4

6

try this,

@Override
    public void onBackPressed() {
        Intent backtoHome = new Intent(Intent.ACTION_MAIN);
        backtoHome.addCategory(Intent.CATEGORY_HOME);
        backtoHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(backtoHome);
    }

Adding this to your Activity, will make it look like your app is responding to a Home Button Click event

Andro Selva
  • 53,136
  • 52
  • 190
  • 238
2

Going to home screen programmatically

to launch home screen

Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);

Note :

This Intent will start the launcher application that the user has defined. Be careful with this because this will look like your application crashed if the user does not expect this.

If you want this to build an exit button from your app please read this article on exit Buttons in Android

Community
  • 1
  • 1
Dheeresh Singh
  • 15,570
  • 3
  • 36
  • 36
0

One line solution

@Override
public void onBackPressed() {
   moveTaskToBack(true);
}

And also see this

Community
  • 1
  • 1
shehzy
  • 2,055
  • 3
  • 22
  • 40
0
@Override
public void onBackPressed()
    //super.onBackPressed();
    NavUtils.navigateUpFromSameTask(this);
}

If something doesn't work like expected try it with uncommented

    super.onBackPressed();