Shubhashis
Shubhashis

Reputation: 10631

Running same Asynctask multiple times sequentially

I am trying to execute same Asynctask sequentially. For example, Let there be an Asynctask A. Now assume A checks if some server is busy or not. If it's busy, it checks again.... And so on. Let's say it checks this for 5 times then let users know that the service is unavailable.
So same Asynctask can obviously be used.
Trying to achieve it with loops may yield unexpected result as according to this link,
Asynctask is a fire-and-forget instance and AsyncTask instances can only be used one time..
So looping 5 times means Asynctask will be called 5 times. But if the server is free on the 2nd attempt, I don't need additional checking. Also android application may hang(mine did). Correct me if I'm wrong on this topic.

Also the answer was, "calling task like new MyAsyncTask().execute("");"
So if i do like this -- for example,

new someAsyncTask() {
            @Override
            protected void onPostExecute(String msg) {
                new someAsyncTask() {
                    @Override
                    protected void onPostExecute(String msg) {
                      ....and so on 5 times.
                   }
               }.execute(this);
            }
        }.execute(this);

It should be called 5 times sequentially and no problems should occur.
Is it the only way to do this or any other solution is present?

Upvotes: 6

Views: 6320

Answers (1)

tachyonflux
tachyonflux

Reputation: 20211

You could use a field variable in the outer class:

private int count;
private void attemptConnect(){
    count = 0;

    new MyTask().execute("");
}

class MyTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... params) {
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        count++;
        if(count < 5){
            new MyTask().execute("");
        }
    }
}

Or pass in a count to the AsyncTask constructor:

private void attemptConnect(){
    new MyTask(0).execute("");
}

class MyTask extends AsyncTask<String, String, String> {
    private int count;

    public MyTask(int count){
        this.count = count;
    }

    @Override
    protected String doInBackground(String... params) {
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        if(count < 4){
            new MyTask(++count).execute("");
        }
    }
}

Upvotes: 4

Related Questions