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...
Try this code: