Search code examples
androidandroid-fragmentsonbackpressed

Onbackpressed close app not closing app after login


My application consist of 2 main activity and 1 secondary activity (login popup)

  1. Activity is PreLogin activity where user have application info and few other things and button for login. When he presses that button, new activity starts as a popup. And if he clicks back there, that activity is closed and user is returned to previous activity.

  2. Activity is PostLogin and there I implemented this function:

My code:

public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        finish();
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    final View coordinatorLayoutView = findViewById(R.id.coordinator);

    Snackbar.make(coordinatorLayoutView, "Press again to exit.", Snackbar.LENGTH_LONG).show();
    new Handler().postDelayed(new Runnable() {


        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;

        }
    }, 5000);
}

This code should close my application but problem is that pressing back button 2 times, the grey screen shows and users need to click back button once more to exit the app.

I'm quite sure problem is somehow connected with my Prelogin activity because when I try noHistory on my Prelogin activity onBackpressed() worked like charm but I can't use that approach because I need to have history on my Prelogin so back button work for Login Popup.


Solution

  • You can just use the simple code below to achieve that.

    @Override
        public void onBackPressed() {
            if (back_pressed + 2000 > System.currentTimeMillis()) {
                //Intent intent = new Intent(Intent.ACTION_MAIN);
                //intent.addCategory(Intent.CATEGORY_HOME);
                //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //startActivity(intent);
                super.onBackPressed();
            } else {
                Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
                back_pressed = System.currentTimeMillis();
            }
        }
    

    Here, 2000 is 2 Seconds, you can change it to whatever value you like. If the back button is pressed within 2 seconds again, then only it will go back.

    You can call the Intent of the previous activity if you want, or you can remove the commented Intent code to go back to the Home Screen.