I want to perform an operation like when i pressed back Button single time then it will move to the selected screen and when i pressed twice Back Button then it will show the dialog and ask for exit.

I tried many examples in stack overflow but none of them are helping me..

navaigation.java

    private int clickCount = 0;
    private long delay = 100;
    Timer timer = new Timer();

    @Override
    public void onBackPressed() {
        if (clickCount == 2) {
            super.onBackPressed();
            timer.cancel();
        } else{
            clickCount++;
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            backButtonHandler();
                        }
                    });
                }

        }, delay);
    }

}




public void backButtonHandler() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            Navigation.this);
    // Setting Dialog Title
    alertDialog.setTitle("Leave application?");
    // Setting Dialog Message
    alertDialog.setMessage("Are you sure you want to leave the application?");
    // Setting Icon to Dialog
    alertDialog.setIcon(R.drawable.m_visit);
    // Setting Positive "Yes" Button
    alertDialog.setPositiveButton("YES",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    // Setting Negative "NO" Button
    alertDialog.setNegativeButton("NO",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to invoke NO event
                    dialog.cancel();
                }
            });
    // Showing Alert Message
    alertDialog.show();
}

I tried this way but it is not working properly...

5

There are 5 best solutions below

6
On BEST ANSWER

Try this code:

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {
private static final int TIME_DELAY = 2000;
private static long back_pressed;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public void onBackPressed() {
    if (back_pressed + TIME_DELAY > System.currentTimeMillis()) {
        super.onBackPressed();
    } 
    else {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you sure, You wanted to exit");
        alertDialogBuilder.setPositiveButton("yes", 
        new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface arg0, int arg1) {
          finish();
        }
       });

        alertDialogBuilder.setNegativeButton("No",new
       DialogInterface.OnClickListener() {
       Override
       public void onClick(DialogInterface dialog, int which) {
        dismiss();
         }
       });

       AlertDialog alertDialog = alertDialogBuilder.create();
       alertDialog.show();
      }    
    }
    back_pressed = System.currentTimeMillis();
}
4
On

Hey check this code I have showed Snackbar if user clicks the back button for the first time.And for second time Application will get exit.

private boolean mIsBackAlreadyPressed;

    @Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else if (mIsBackAlreadyPressed) {
            mIsBackAlreadyPressed = false;
            super.onBackPressed();
            overridePendingTransition(R.anim.pull_in_left, R.anim.push_out_right);
        } else {
            mIsBackAlreadyPressed = true;
            Snackbar.make(drawer, R.string.press_back_twice, Snackbar.LENGTH_SHORT).show();

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mIsBackAlreadyPressed = false;
                }
            }, 2000);
        }
    }

Hope this help.Happy coding.

2
On

Can you try this

 private boolean exit=false;//declare in public

public void onBackPressed() {
    // TODO Auto-generated method stub
    if (exit) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    } else {
        Toast.makeText(this, "Tap again to exit.", Toast.LENGTH_SHORT)
                .show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);
    }
}
0
On

try this:

    private Boolean close_app = false;
@Override
    public void onBackPressed() {
        if (close_app) {
            //finish(); // pressed twice
            backButtonHandler();
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            close_app = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    close_app = false;
                }
            }, 3 * 1000);
        }
    }

The Handler here handles back presses, it simply shows a Toast, and if there is another back press within 3 seconds, it shows the dialog for exiting the application

2
On

if you press back then u can go where ever u want

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(Exit.this,Home.class);
    startActivity(intent);
    finish();
}

If u double click back button now u can exit try below code

private Boolean exit = false;
@Override
public void onBackPressed() {
    if (exit) {
        finish(); // finish activity
    } else {
        Toast.makeText(this, "Press Back again to Exit.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);

    }

}