tags:

views:

58

answers:

1

I am Developing an App that parses data from HTML. One of the data that is parsed is an integer that increases over time and rather than constantly requesting the data I would like to have a task that intervals the integer. Due to the fact that I need the value updated into a TextView I decided to go with an AsyncTask rather than a Timer.

My issue is I want to be able to restart my task once I know that it has finished, or if it is currently RUNNING simply avoid manipulating it.

Here is my AsyncTask:

class TurnsUpdate extends AsyncTask<Void, Integer, Exception>
{
    protected void onPreExecute()
    {
        turns = Integer.parseInt(DATABASE.getValue("turns").replaceAll(" T", ""));
    }

    protected Exception doInBackground(Void...voids)
    {
        while (turns < maxTurns)
        {
            try
            {
                Thread.sleep(sleep);
            }
            catch (InterruptedException e)
            {
                return e;
            }

            turns++;
            publishProgress(turns);
        }
        return null;
    }

    protected void onProgressUpdate(Integer... turns)
    {
        infoTurns.setText(Integer.toString(turns[0]) + " T");
    }

    protected void onPostExecute(Exception e)
    {
        vibrator.vibrate(500);
    }
}

My attempt to start or avoid:

  if ((HOME.updateTurns == null || HOME.updateTurns.getStatus() == AsyncTask.Status.FINISHED) && HOME.updateTurns.getStatus() != AsyncTask.Status.RUNNING)
    {
        HOME.updateTurns = (UpdateTurns) new UpdateTurns();
        HOME.updateTurns.execute();
    }

Am I going about this correctly?

+1  A: 

Have you tried just making a recursive call:

new UpdateTurns().execute() 

in onPostExecute? Technically it should work since any code in onPostExecute is run on the UI thread as opposed to the thread created in AsyncTask.

AndrewKS
Well that actually worked. Thanks.
Alejandro Huerta