17

Is it possible to move the app in background when we click on device back button in android?

background means application moves to screen(application) from where it launches ?

Roll no1
  • 1,315
  • 1
  • 16
  • 23

3 Answers3

39

Try Using

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    switch(keyCode)
    {
        case KeyEvent.KEYCODE_BACK:

            moveTaskToBack(true);

            return true;
    }
    return false;
}
Nishant Rajput
  • 2,053
  • 16
  • 28
17
@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

Kotlin

override fun onCreate(savedInstanceState: Bundle?) {
    onBackPressedDispatcher.addCallback(this) { moveTaskToBack(true) }
}
dan_flo10
  • 312
  • 2
  • 10
8

I will prefer to use below code to move application in background

       @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        switch(keyCode)
        {
            case KeyEvent.KEYCODE_BACK:
              if(isTaskRoot()) {
               Intent homeIntent = new Intent(Intent.ACTION_MAIN);
               homeIntent.addCategory(Intent.CATEGORY_HOME);
               homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
               startActivity(homeIntent);
               return true;
                }
            else {
             super.keyDown(keyCode,event);
             return false;      
        }

    default: 
    super.keyDown(keyCode,event);
           return false;
 }

}
Roll no1
  • 1,315
  • 1
  • 16
  • 23