我有一个进度对话框,在一些运行过程中显示。
如果动作在给定时间内没有执行,我想关闭对话框和动作。我该如何实现呢?
我目前有这两种方法,它们停止并启动我的异步操作和对话框:
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();
}
答案 0 :(得分:1)
你可以制作一个简单的计时器:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
stopAction();
}
};
timer.schedule(task, 1000);
答案 1 :(得分:1)
我认为你应该使用Thread
或TimerTask
。暂停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;
}
}