Running the same Asynctask several times in a row

I am trying to execute the same Asynctask sequentially. For example, let Asynctask A be . Now suppose A checks to see if any server is busy or not. If he is busy, he checks again ... And so on. Say he checks this 5 times, and then informs users that the service is unavailable.
Obviously the same Asynctask can be used.
Attempting to achieve this using loops can lead to an unexpected result, since according to this the link ,
Asynctask is an instance with fire and oblivion, and AsyncTask instances can only be used once. .
Thus, a loop of 5 times means that Asynctask will be called 5 times. But if the server is free in the second attempt, I do not need additional verification. Also, the Android application can hang (mine did). Correct me if I am wrong in this thread.

There was also an answer: " calling task like new MyAsyncTask().execute(""); "
Therefore, if I like it - 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 in a row and there should be no problems.
Is this the only way to do this or is there any other solution present?

+6
source share
1 answer

You can use the 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 the counter 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(""); } } } 
+4
source

Source: https://habr.com/ru/post/986418/


All Articles