Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to timeout an AlertDialog in Android?

How can i handle timeout in an alertdialog. It has the standard yes/no button but i want to call the no button code if the user doesn't press anything in 5 minutes. I've looked at the class in Android page and there's no function which can be called to set a timeout.

like image 615
Naveen Sharma Avatar asked Jul 13 '13 09:07

Naveen Sharma


People also ask

Is AlertDialog deprecated?

A simple dialog containing an DatePicker . This class was deprecated in API level 26.

What is AlertDialog message?

AlertDialog. A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. DatePickerDialog or TimePickerDialog. A dialog with a pre-defined UI that allows the user to select a date or time.


2 Answers

I have used a Dialog for achieving this instead of using the alert dialog.

new Handler().postDelayed(new Runnable() {

    public void run() {
        yourDialogObj.dismiss();
    }
}, 2000);

here 2000 is miliseconds,

Hope this helps

like image 115
Qadir Hussain Avatar answered Sep 30 '22 01:09

Qadir Hussain


Here is an example, hope be helpful.

public class MainActivity extends Activity {

    static final int TIME_OUT = 5000;

    static final int MSG_DISMISS_DIALOG = 0;

    private AlertDialog mAlertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createDialog();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case MSG_DISMISS_DIALOG:
                if (mAlertDialog != null && mAlertDialog.isShowing()) {
                    mAlertDialog.dismiss();
                }
                break;

            default:
                break;
            }
        }
    };

    private void createDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("OK", null)
            .setNegativeButton("cacel", null);
        mAlertDialog = builder.create();
        mAlertDialog.show();
        // dismiss dialog in TIME_OUT ms
        mHandler.sendEmptyMessageDelayed(MSG_DISMISS_DIALOG, TIME_OUT);
    }
}
like image 43
iStar Avatar answered Sep 30 '22 02:09

iStar