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 on开发者_Go百科PostExecute(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?
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.
I kept getting an exception when trying to call .execute() on an AsyncTask with a status of FINISHED. I finally found this line in the API:
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Source: http://developer.android.com/reference/android/os/AsyncTask.html under 'Threading Rules'
精彩评论