0

I am currently using this in my MainActivity for back press twice to exit from the pp. It works fine but the problem is after second press to exit from app, the app exits coorectly with a black screen which is not convinient for user. How do I overcome this problem?

@Override
    public void onBackPressed() {

        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {

            getSupportFragmentManager().popBackStack();
            navigationView.getMenu().getItem(0).setChecked(true); //set the background to the correct place
        } else if (!doubleBackToExitPressedOnce) {

            this.doubleBackToExitPressedOnce = true;

            Toast.makeText(this, R.string.press_twice_to_exit, Toast.LENGTH_SHORT).show();

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
        } else {

            super.onBackPressed();
            System.exit(0);
        }
    }
  • 3
    Do not use System.exit(0) on Android. I think this will cause your black screen. Use finish() to stop an Activity. If you want to clear all open activities, please have a look at this question: http://stackoverflow.com/questions/16480867/system-exit0-doesnt-close-all-my-activities – Christopher Jan 17 '17 at 15:31

2 Answers2

0

After first else use

if (doubleBackToExitPressedOnce) {
    super.onBackPressed();
    return;
}

this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

new Handler().postDelayed(new Runnable() {

    @Override
    public void run() {
        doubleBackToExitPressedOnce=false;                       
    }
}, 2000);
Arpit Jain
  • 94
  • 1
  • 5
0

Remove System.exit(0) and use finish():

 } else {

     //removed backPressed and System.exit(0)
     finish();
 }
W4R10CK
  • 5,502
  • 2
  • 19
  • 30