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 .
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.
executeOnExecutor(AsyncTask. THREAD_POOL_EXECUTOR); So in order to execute multiple AsyncTask in parallel, we have to use THREAD_POOL_EXECUTOR and execute the AsyncTasks.
To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask myTask = new MyTask(); myTask. execute(); In the above snippet we've used a sample classname that extends AsyncTask and execute method is used to start the background thread.
The following code snippet must be present in the MainActivity class in order to launch an AsyncTask. MyTask myTask = new MyTask(); myTask. execute(); The execute method is used to start the background thread in the excerpt above, where we've used a sample class name that extends AsyncTask.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With