1

I want hide my app, if press BACK button.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  
{
     if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
     {
        this.moveTaskToBack(true);
        return true;
     }
    return super.onKeyDown(keyCode, event);
}

But my app close. What i do wrong?

plsgogame
  • 1,334
  • 15
  • 28

4 Answers4

1

You must override onBackPressed() method of Activity class. Here is a sample of code:

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

Also you must override onBackPressed() method in child activities:

@Override
public void onBackPressed() {
    this.getParent().onBackPressed();   
}
kord
  • 482
  • 3
  • 12
0

By keeping activity at back do you mean the back button should act like a home button. If that is so 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, and your app will hide but not close.

Ankit Aggarwal
  • 2,367
  • 24
  • 30
-1

you can try this:

 Intent intent2 = new Intent(getApplicationContext(), MainActivity.class);
        intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent2.putExtra("EXIT", true);
        startActivity(intent2);

And into your MainActivity:

Write this in onCreate()

if (getIntent().getBooleanExtra("EXIT", false)) {
            finish();
        }

Try this. It will send you to the HomeScreen.

Narendra Pal
  • 6,474
  • 13
  • 49
  • 85
-3

I'd recommend you reconsider. If every application were allowed to use the buttons however they wish, it would be impossible to maintain a certain consistency in user experience.

The physical buttons should work the same for all applications.A prof told me once: "Your app is nothing special." Not in the sense that it's not great, just that it should, optimally, follow certain standards so as to not confuse users.

Cos
  • 1,649
  • 1
  • 27
  • 50