Android关闭对话5秒后?

时间:2013-01-21 19:24:37

标签: java android dialog schedule

我正在开发辅助功能应用。当用户想要离开应用程序时,我会显示一个对话框,他必须确认他要离开,如果他在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秒关闭对话框?

8 个答案:

答案 0 :(得分:71)

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);

答案 1 :(得分:19)

使用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();

答案 2 :(得分:4)

这是代码,请参阅此link

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get button
        Button btnShow = (Button)findViewById(R.id.showdialog);
        btnShow.setOnClickListener(new View.OnClickListener() {
            //on click listener
            @Override
            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");
                builder.setCancelable(true);

                final AlertDialog closedialog= builder.create();

                closedialog.show();

                final Timer timer2 = new Timer();
                timer2.schedule(new TimerTask() {
                    public void run() {
                        closedialog.dismiss(); 
                        timer2.cancel(); //this will cancel the timer of the system
                    }
                }, 5000); // the timer will count 5 seconds....

            }
        });
    }
}

快乐的编码!

答案 3 :(得分:4)

最近,但我认为这对于在其应用程序中使用RxJava的任何人都有用。

RxJava带有一个名为.timer()的运算符,它将创建一个Observable,它将在给定的持续时间后仅触发onNext()一次,然后调用onComplete()。这非常有用,可以避免创建Handler或Runnable。

有关此运营商的更多信息,请参阅ReactiveX Documentation

// Wait afterDelay milliseconds before triggering call
Subscription subscription = Observable
        .timer(5000, TimeUnit.MILLISECONDS) // 5000ms = 5s
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                // Remove your AlertDialog here
            }
        });

您可以通过在按钮单击时从observable取消订阅来取消计时器触发的行为。因此,如果用户手动关闭警报,请调用subscription.unsubscribe(),它具有取消计时器的效果。

答案 4 :(得分:0)

我添加了自动关闭,并将正面按钮文字中显示的剩余时间添加到AlertDialog

AlertDialog dialog = new AlertDialog.Builder(getContext())
        .setTitle(R.string.display_locked_title)
        .setMessage(R.string.display_locked_message)
        .setPositiveButton(R.string.button_dismiss, null)
        .create();

dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface dialog) {
        final Button positiveButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        final CharSequence positiveButtonText = positiveButton.getText();
        new CountDownTimer(AUTO_DISMISS_MILLIS, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                positiveButton.setText(String.format(Locale.getDefault(), "%s (%d)",
                        positiveButtonText,
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1));
            }

            @Override
            public void onFinish() {
                dismiss();
            }
        }.start();

    }
});

答案 5 :(得分:0)

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.game_message);
        game_message = builder.create();
        game_message.show();


        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            public void run() {
                game_message.dismiss(); // when the task active then close the dialog
                t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
            }
        }, 5000);

参考:https://xjaphx.wordpress.com/2011/07/13/auto-close-dialog-after-a-specific-time/

答案 6 :(得分:0)

对于受Tahirhan的回答启发的Kotlin。 这就是我当前项目的工作方式。希望它会在不久的将来对别人有所帮助。 我在一个片段中调用此函数。编码愉快!

 fun showAlert(message: String) {
        val builder = AlertDialog.Builder(activity)
        builder.setMessage(message)

        val alert = builder.create()
        alert.show()

        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                alert.dismiss()
                timer.cancel()
            }
        }, 5000)
    }

答案 7 :(得分:-3)

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();

然后调用dismiss meth it work

alertDialog .dismiss();