In my app, I show the push notification as a Dialog that has two buttons named Yes and No. I need to show a timer (20 seconds) running in the dialog's title.
If the user clicks Yes, it should go to an activity.
If the user clicks No, the dialog gets canceled before timer ends.
When the countdown finishes,the Dialog should disappear. How should I implement this?
Here is my Alert dialog Method
public void showAlertDialog(final Context context, String title, String message,
Boolean status) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.fail);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
//alertDialog.setIcon(R.drawable.counter);
alertDialog.show();
}
I wouldn't recommend adding the countdown into the dialog's title. If you instead add it to the No button, it is more obvious for the user what will happen when the countdown finishes.
Here's code for an AlertDialog that does just that.
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Notification Title")
.setMessage("Do you really want to delete the file?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO: Add positive button action code here
}
})
.setNegativeButton(android.R.string.no, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
private static final int AUTO_DISMISS_MILLIS = 6000;
@Override
public void onShow(final DialogInterface dialog) {
final Button defaultButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
final CharSequence negativeButtonText = defaultButton.getText();
new CountDownTimer(AUTO_DISMISS_MILLIS, 100) {
@Override
public void onTick(long millisUntilFinished) {
defaultButton.setText(String.format(
Locale.getDefault(), "%s (%d)",
negativeButtonText,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1 //add one so it never displays zero
));
}
@Override
public void onFinish() {
if (((AlertDialog) dialog).isShowing()) {
dialog.dismiss();
}
}
}.start();
}
});
dialog.show();
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