Search code examples
androidonbackpressed

OnBackPressed recreates the activity instead of finishing it


   @Override
    public void onBackPressed() {
        if (searchView.isSearchOpen()) {
            searchView.closeSearch();
        } else if (activeFragment != homeFragment) {
            goToHomeFragment();
        } else {
            super.onBackPressed();
            finish();
        }
    }

In the above code, when reached in else block, the activity recreate itself instead of finishing itself and exit. The hosted activity has 4 fragments but I guess there's nothing to do with the fragments. So any idea about what went wrong? Any Suggestions? Thank you for paying attention.

EDITED : according to Manzurul Hoque Rumi, moveTaskToBack(true) really did the work. Issue Neutralized. I want to thank everyone who has answered my question.


Solution

  • Remove finish() and try

    @Override
        public void onBackPressed() {
            if (searchView.isSearchOpen()) {
                searchView.closeSearch();
            } else if (activeFragment != homeFragment) {
                goToHomeFragment();
            } else {
                moveTaskToBack(true);
            }
        }