安卓关闭对话框5秒后?

2022-09-01 03:26:03

我正在开发一个辅助功能应用程序。当用户想要离开应用程序时,我会显示一个对话框,他必须确认他是否要离开,如果他在5秒后没有确认,对话框应该会自动关闭(因为用户可能不小心打开了它)。这类似于更改屏幕分辨率时在 Windows 上发生的情况(将显示警报,如果不确认,它将恢复为以前的配置)。

以下是我显示对话框的方式:

AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Leaving launcher").setMessage("Are you sure you want to leave the launcher?");
            dialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                    exitLauncher();
                }
            });
            dialog.create().show();

如何在显示对话框5秒后关闭对话框?


答案 1
final AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Leaving launcher").setMessage("Are you sure you want to leave the launcher?");
dialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int whichButton) {
        exitLauncher();
    }
});     
final AlertDialog alert = dialog.create();
alert.show();

// Hide after some seconds
final Handler handler  = new Handler();
final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        if (alert.isShowing()) {
            alert.dismiss();
        }
    }
};

alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
    @Override
    public void onDismiss(DialogInterface dialog) {
        handler.removeCallbacks(runnable);
    }
});

handler.postDelayed(runnable, 10000);

答案 2

用来实现。CountDownTimer

      final AlertDialog.Builder dialog = new AlertDialog.Builder(this)
            .setTitle("Leaving launcher").setMessage(
                    "Are you sure you want to leave the launcher?");
       dialog.setPositiveButton("Confirm",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                     exitLauncher();

                }
            });
    final AlertDialog alert = dialog.create();
    alert.show();

    new CountDownTimer(5000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub

            alert.dismiss();
        }
    }.start();

推荐