0

I'm trying to exit my application when the user double taps the HardWare Back Button, I've used the following code in my application:

    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        Dashboard_Activity.this.finish();
        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);

Here when the user Double Taps the Hardware Back Button the same activity appears again and again, but the app doesn't exits. Can you please help me fixing the issue.

Vishwajit Palankar
  • 3,033
  • 3
  • 28
  • 48
Parthiban M
  • 1,104
  • 1
  • 10
  • 30

3 Answers3

0

Try the following:

private static long back_pressed;

    @Override
    public void onBackPressed()
    {
        if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
        else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
        back_pressed = System.currentTimeMillis();
    }

Source

fida1989
  • 3,234
  • 1
  • 27
  • 30
0

Try This Method Any where in your code Out side of Oncreate, Working for me

        @Override
        public void onBackPressed() 
        {
            try
            {

            //pop up Window closed. 
            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);

            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }   
Android Dev
  • 421
  • 8
  • 26
0

First, create SplashScreenActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    finish();
}

Then in your activity(or in BaseActivity) add this variable as class member:

private long milis;

And override onBackPressed():

@Override
public void onBackPressed() {
    if(milis + 2000 > System.currentTimeMillis()){
        Intent intent = new Intent(this, SplashScreenActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }else{
        milis = System.currentTimeMillis();
    }
}
Aleksandr
  • 4,906
  • 4
  • 32
  • 47