How do i display a countdown timer in my alert box .i want to notify the user that the session will end in 5 minutes and show a timer running in the alert pop up box in android
The following code creates a prompt as you described. It adds a count down timer to a default action button.
Dialog Listener Class
private static class DialogTimeoutListener
implements DialogInterface.OnShowListener, DialogInterface.OnDismissListener {
private static final int AUTO_DISMISS_MILLIS = 5 * 60 * 1000;
private CountDownTimer mCountDownTimer;
@Override
public void onShow(final DialogInterface dialog) {
final Button defaultButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
final CharSequence positiveButtonText = defaultButton.getText();
mCountDownTimer = new CountDownTimer(AUTO_DISMISS_MILLIS, 100) {
@Override
public void onTick(long millisUntilFinished) {
if (millisUntilFinished > 60000) {
defaultButton.setText(String.format(
Locale.getDefault(), "%s (%d:%02d)",
positiveButtonText,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished % 60000)
));
} else {
defaultButton.setText(String.format(
Locale.getDefault(), "%s (%d)",
positiveButtonText,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1 //add one so it never displays zero
));
}
}
@Override
public void onFinish() {
if (((AlertDialog) dialog).isShowing()) {
// TODO: call your logout method
dialog.dismiss();
}
}
};
mCountDownTimer.start();
}
@Override
public void onDismiss(DialogInterface dialog) {
mCountDownTimer.cancel();
}
Alert Dialog
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Session Timeout")
.setMessage("Due to inactivity, you will soon be logged out.")
.setPositiveButton("Extend Session", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO: call your log out method
}
})
.setNegativeButton("Log Out Now", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO: call method to extend session
}
})
.create();
DialogTimeoutListener listener = new DialogTimeoutListener();
dialog.setOnShowListener(listener);
dialog.setOnDismissListener(listener);
dialog.show();
Create a Custom dialog with a TextView on it.
and update that code with the help of CountDownTimer class like this.
new CountDownTimer(300000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
you can dismiss your dialog in onFinish().
for more detail you can follow this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With