Skip to content

Dismiss alert dialog after time

How do I add an automatic dismiss dialog after a time to the show alert function?

public void showAlert(String title, String message, Integer seconds) {
        new IonAlert(context, IonAlert.SUCCESS_TYPE)
                .setTitleText(title)
                .setContentText(message)
                .show();
}

Answer

Handler class provides a method called postDelayed(). It allows us to dealy an event (in your case, event is to dismiss the dialog).

    public void showAlert(String title, String message, Integer seconds) {
        final IonAlert ionAlertDialog = new IonAlert(context, IonAlert.SUCCESS_TYPE)
            .setTitleText(title)
            .setContentText(message)
            .show();
    
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ionAlertDialog.dismiss();
            }
        }, seconds ? seconds * 1000 : 5000); //default 5sec
    }