Saturday, June 6, 2015

// //

Auto-close Alert dialog programmatically

What is AlertDialog?
An Alertdialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.
 What are we going to do? 
This time we will close the alertdialog programmatically because not like Toast which is auto closed after 1-2 seconds, Dialog by default is not auto closed and doesn’t have any settings for auto closing. If ever, you want your Dialog to be programmatically close then you may use a Timer to achieve it. Here a sample:

And then Click the Button:
close alertdialog programmatically android
The alertdioalog will close after 5 seconds
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        // get button
        Button btnShow = (Button)findViewById(;
        btnShow.setOnClickListener(new View.OnClickListener() {
         //on click listener
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setTitle("How to close alertdialog programmatically");
                builder.setMessage("5 second dialog will close automatically");
                final AlertDialog closedialog= builder.create();
                final Timer timer2 = new Timer();
                timer2.schedule(new TimerTask() {
                    public void run() {
                        timer2.cancel(); //this will cancel the timer of the system
                }, 5000); // the timer will count 5 seconds....

You may also like : Alertdialog Media Player, Start, Stop(How To Set MediaPlayer Volume Programmatically?)