Reputation: 31
I am trying to write a code to exit the app when double pressing the back button. I don't want to call super.onBackPressed(); since it takes me back to the first activity which is splash screen, and I don't want that, I want to exit the app on double pressing. Thank you.
This is my onBackPressed method:
@Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else{
if (doubleBackToExitPressedOnce) {
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
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);
}
}
Upvotes: 1
Views: 149
Reputation: 502
Define two class level variables like private long TIME_DELAY = 2000; private long back_pressed;
on OnBackPressed() method, write below code.
if (back_pressed + TIME_DELAY > System.currentTimeMillis()) { finish(); super.onBackPressed();
} else {
Toast.makeText(getBaseContext(), R.string.press_back_again_to_exit,
Toast.LENGTH_SHORT).show();
}
back_pressed = System.currentTimeMillis();
Upvotes: 1
Reputation: 521
just use finish()
after launching the intent to the next activity:
startActivity(new Intent(this, NextActivity.class));
//Below will enable the app to exit if back is pressed
finish();
Upvotes: 0
Reputation: 11
If you didn't call finish()
before you start your second Activity from the first one, it will remain, so when you close your second one,
the program takes you back to the first one, which is not finished yet.
So call finish()
after startActivity()
in your first Activity
Upvotes: 1