Search code examples
androidandroid-activity

how to emulate home button on back button pressed


I'm trying to make my app not close when the user pressed the back button and remain in the same state at least for a while, like the home button. I searched and some people suggested to do this.

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

but this didn't help. I have to mention the activity I'm using this code on is not the LAUNCHER activity and before this activity, there is a splash screen.

what am I doing wrong?


Solution

  • Try my code in your activity.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(TAG, "onKeyDown: ");
        if(keyCode == KeyEvent.KEYCODE_BACK){
            goHome();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    private void goHome() {
        Intent i = new Intent(Intent.ACTION_MAIN);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addCategory(Intent.CATEGORY_HOME);
        startActivity(i);
    }
    

    Do start the home screen when key back down.