Android app: calling AsyncTask twice?

I use AsyncTask and fairly common Android code to retrieve the contents of a remote web page. Based on this returned content, I can call another page.

http://developer.android.com/reference/android/os/AsyncTask.html

My debug lines should be printed as follows:

1> StartA() 2> onPreExecute 3> doInBackground 4> onPostExecute Note: Code here will call EndA() 5> EndA() 6> 7> StartB() 8> onPreExecute 9> doInBackground 10> onPostExecute Note: Code here will call EndB() 11> EndB() 

Is this impossible to do? I make all of the above work ... EXCEPT I get one extra call to EndB (), which appears between lines 8 and 9.

I can’t understand for life why. It seems that it should not call EndB () twice. And this definitely should not be called BEFORE 9 and 10.

 private void StartA() { Debug("StartA()"); g_GetWhat = 1; DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://google.com" }); } private void EndA() { Debug("EndA()"); StartB(); } private void StartB() { Debug("StartB()"); g_GetWhat = 2; DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://yahoo.com" }); } private void EndB() { Debug("EndB()"); } 

//////////////////////////////////////////////////// /

 private class DownloadWebPageTask extends AsyncTask<String, Void, String> { protected void onPreExecute() { Debug("onPreExecute()"); } protected String doInBackground(String... urls) { Debug("doInBackground()"); } protected void onPostExecute(String result) { Debug("onPostExecute()"); if(g_GetWhat == 1) { EndA(); } if(g_GetWhat == 2) { EndB(); } } } 
+4
source share
2 answers

You can execute an AsyncTask instance only once. You are actually creating two instances, but you should call it so that it is never called:

 new DownloadWebPageTask().execute(new String[] { "http://yahoo.com" }); new DownloadWebPageTask().execute(new String[] { "http://google.com" }); 

instead of this:

 DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://google.com" }); 

I think you ran into a problem here:

 private void EndA() { Debug("EndA()"); StartB(); } 

Your value for g_GetWhat changes as soon as StartB begins. Therefore, when execution returns from EndA() , the following if statement evaluates to true, since the value of g_GetWhat has changed.

 if(g_GetWhat == 1) { EndA(); } if(g_GetWhat == 2) { EndB(); } 

The value of g_GetWhat is actually 2, so you see the result you see. You must pass g_GetWhat to your AsyncTask when you call it, and make it a task instance variable.

+5
source

If you need to perform several simultaneous operations in the background, you should use the service class in Android (not IntentService, since calls are in the queue and do not start at the same time).

0
source

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


All Articles