In this tutorial we are going to learn how to implement pressing back again to exit application. Am sure this is not the first time you are coming across this concept. Many apps tend to use this behavior to handle stuff in case user presses back button accidentally. I haven’t seen this concept annoying. Anyway let’s jump into the main business of the day.

You may also like:

1. Create New Project

Create new android application and name it PressBackAgainToExit, please note, you can name your application anything you want.

For this tutorial, there is no special permissions required so we will concentrate only with MainActivity.



import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private static boolean userPressedBackAgain = false;

protected void onCreate(Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) findViewById(;


public void onBackPressed() {
if (!userPressedBackAgain) {
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
userPressedBackAgain = true;
} else {

new CountDownTimer(3000, 1000) {

public void onTick(long millisUntilFinished) {


public void onFinish() {
userPressedBackAgain = false;



2. Explanation

First we have created a boolean variable userPressedBackAgain = false. This variable will enable us to know when user pressed back again. To detect when user presses back button, we overrided onBackPressed(). If the variable is false, update userPressedBackAgain = true, so that when user presses back within 3 seconds, the application will exit. We have created timer to make sure, if user delays for at least 3 seconds, system will request them to press back again.

Thant’s how simple it is. Please let me get your reactions in the commenting system below. Thanks

Similar Posts