Ocultar el diálogo de progreso solo por un tiempo finito/fijo

I have a progress dialog which is shown during some running action.

If the action hasn't executed for a given time, I want to dismiss the dialog and the action. How do I implement this?

I currently have these two methods, which stop and start my async action and dialog:

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

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

i.e. I want to do something like this when the time is out:

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

preguntado el 28 de agosto de 12 a las 11:08

Use TimerTask it will make your life easy. Run a task after fixed time which will cancel the async task if not started within given time. -

2 Respuestas

You can make a simple timer:

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

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

timer.schedule(task, 1000);

Respondido 28 ago 12, 11:08

Sorry. Forgot to add, that my async action can be stopped before time is out. Then I need to cancel my timer too. Is it then enough to simple cancel it in stopAction() method? - Ksice

in the postExecute of your asyncTask, you can call timer.cancel(); - AlexMok

Creo que deberías usar un Thread o con una TimerTask. Pause it X seconds, then if your task is not yet finished, force finish it and dismiss dialog.

So one implementation could be :

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

Respondido 28 ago 12, 11:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.