Reputation: 1087
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.
Upvotes: 5
Views: 10032
Reputation: 8856
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
Upvotes: 10
Reputation: 1120
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);
}
}
Upvotes: 6