【问题标题】:Hide progress dialog only for a finite/fixed time仅在有限/固定时间内隐藏进度对话框
【发布时间】:2012-08-28 10:13:53
【问题描述】:

我有一个进度对话框,在某些运行操作期间显示。

如果操作在给定时间内没有执行,我想关闭对话框和操作。我该如何实现?

我目前有这两种方法,它们可以停止和启动我的异步操作和对话框:

private void startAction()
{
    if (!actionStarted) {
        showDialog(DIALOG_ACTION);
        runMyAsyncTask();
        actionStarted = true;
    }
}

private void stopAction()
{
    if (actionStarted) {
        stopMyAsyncTask();
        actionStarted = false;
        dismissDialog(DIALOG_ACTION);
    }
}

即时间到了我想做这样的事情:

onTimesOut()
{
    stopAction();
    doSomeOtherThing();
}

【问题讨论】:

  • 使用 TimerTask 会让你的生活变得轻松。在固定时间后运行任务,如果在给定时间内未启动,则将取消异步任务。

标签: android timeout progressdialog


【解决方案1】:

你可以做一个简单的计时器:

Timer timer = new Timer();
TimerTask task = new TimerTask() {

    @Override
    public void run() {
        stopAction();
    }
};

timer.schedule(task, 1000);

【讨论】:

  • 对不起。忘了补充,我的异步操作可以在时间结束之前停止。然后我也需要取消我的计时器。那么在 stopAction() 方法中简单地取消它就足够了吗?
  • 在你的asyncTask的postExecute中,你可以调用timer.cancel();
【解决方案2】:

我认为您应该使用ThreadTimerTask。暂停 X 秒,然后如果您的任务尚未完成,请强制完成并关闭对话框。

所以一种实现可能是:

private void startAction() {
    if (!actionStarted) {
        actionStarted = true;
        showDialog(DIALOG_ACTION); //This android method is deprecated
        //You should implement your own method for creating your dialog
        //Run some async worker here...
        TimerTask task = new TimerTask() {
            public void run() {
                if (!actionFinished) {
                    stopAction();
                    //Do other stuff you need...
                }
            }
        });
        Timer timer = new Timer();
        timer.schedule(task, 5000); //will be executed 5 seconds later
    }
}

private void stopAction() {
    if (!actionFinished) {
        //Stop your async worker
        //dismiss dialog
        actionFinished = true;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多