RockOnRockOut
RockOnRockOut

Reputation: 761

Calling the same AsyncTask repeatedly

Here's what I'm trying to do: check a certain website periodically, parse the XML and make the phone vibrate if some conditions are met. I have an AsyncTask where I declared an XmlPullParser - I go over the XML tags and once I find the tag I'm interested in, it checks the value and makes the phone vibrate if that value is in the range I want it to be; however I ran into a catch-22 when trying to run it repeatedly.

I was looking at this StackOverflow post and went with that implementation, but here's what happens:

In onStart I have a startTimer function which looks like this:

private synchronized void startTimer(final Context context){
    timer = new Timer();
    TimerTask task = new TimerTask(){
        @Override
        public void run(){
            executing.set(true);
            functionThatExecutesAsyncTask();
        }
    };
    timer.schedule(task, 01, updateFrequency);
}

The first issue I ran into with this was that I had a new timer created each time I would switch to the app (or flipping the screen), each executing the AsyncTask over the updateFrequency. There were also five AsyncTasks (all listed as "WAITING") in the Threads debugging window, as if each timer created a new task rather than the same one; surprisingly, while I had more than 5 timers, I never had more than 5 tasks, for some reason. To solve the issue of multiple timers, I decided to override onStop and get rid of the existing timer (which would also help in case I'm flipping my phone and want the new timer to call the task):

@Override
public void onStop() {
    super.onStop();
    if(timer != null) {
        timer.cancel();
        timer.purge();
        timer = null;
    }
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    AppIndex.AppIndexApi.end(client, getIndexApiAction());
    client.disconnect();
}

The problem here is obvious: even though additional timers aren't created, I also don't have anything to make the phone vibrate at defined intervals as every single timer is destroyed when the app stops. It also didn't solve the problem of multiple AsyncTasks being created.

Here are the questions:

Upvotes: 0

Views: 306

Answers (1)

Trash Can
Trash Can

Reputation: 6814

If timer is null, we know it does not exist yet, so safe to create a new one. timer is null in these cases:

  • Your app is starting "fresh"
  • Your app was destroyed by android because it was idle(in the background) for awhile.

if (timer == null) { startTimer(this); }

Upvotes: 1

Related Questions