Issue
I have two Activity
s (mainActivity
& downloadActivity
) and I have 2 AsyncTask
s in downloadActivity
In downloadActivity
first it execute getFileAsyncTask
for reading a JSON file for adding some images and create a ListView
from images, if user clicks on an image, the downloadAsyncTask
was called and it starts to download something from the internet.
My problem is here: when the second AsyncTask
is running I go back to mainActivity
and comeback again to downloadActivity
the first AsyncTask
wasn't called until the downloadAsyncTask
completed.
public class downloadActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
new getFileAsyncTask().execute();
...
}
private class getFileAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//fetch a json file from internet and add images in ListView
return null;
}
}
//there is a Base Adapter class
//if user clicks on an image it calls this downloadAsyncTask.execute()
private class downloadAsyncTask extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPreExecute() {
//download the file
}
}
@Override
protected Void doInBackground(Void... unused) {
//download the file
}
}
note: I want to write something like shopping apps. For example, user can download file and surf into shop to see products .
Solution
If you want to run multiple AsyncTasks
in parallel, you can call executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
instead of execute()
on your task. By default, AsyncTasks
run in serial, first come first serve.
Be careful that the two threads do not interact on the same data, this can cause some strange and hard to trace errors.
Answered By - Andrew Schuster
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.