I'm trying to run two AsyncTasks at the same time. (Platform is Android 1.5, HTC Hero.) However, only the first gets executed. Here's a simple snippet to describe my problem:
public class AndroidJunk extends Activity {
class PrinterTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String ... x) {
while (true) {
System.out.println(x[0]);
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new PrinterTask().execute("bar bar bar");
new PrinterTask().execute("foo foo foo");
System.out.println("onCreate() is done.");
}
}
The output I expect is:
onCreate() is done.
bar bar bar
foo foo foo
bar bar bar
foo foo foo
And so on. However, what I get is:
onCreate() is done.
bar bar bar
bar bar bar
bar bar bar
The second AsyncTask never gets executed. If I change the order of the execute() statements, only the foo task will produce output.
Am I missing something obvious here and/or doing something stupid? Is it not possible to run two AsyncTasks at the same time?
Edit: I realized the phone in question runs Android 1.5, I updated the problem descr. accordingly. I don't have this problem with an HTC Hero running Android 2.1. Hmmm ...
Just to include the latest update (UPDATE 4) in @Arhimed 's immaculate answer in the very good summary of @sulai:
Read More https://www.shaikhutech.com/2018/12/biggest-problem-when-it-comes-to-run.html
It is posible. My android device version is 4.0.4 and android.os.Build.VERSION.SDK_INT is 15
I have 3 spinners
And also I have a Async-Tack class.
Here is my spinner loading code
This is working perfectly. One by one my spinners loaded. I didn't user executeOnExecutor.
Here is my Async-task class
Making @sulai suggestion more generic :
This allows for parallel execution on all android versions with API 4+ (Android 1.6+):
This is a summary of Arhimed's excellent answer.
Please make sure you use API level 11 or higher as your project build target. In Eclipse, that is
Project > Properties > Android > Project Build Target
. This will not break backward compatibility to lower API levels. Don't worry, you will get Lint errors if your accidentally use features introduced later thanminSdkVersion
. If you really want to use features introduced later thanminSdkVersion
, you can suppress those errors using annotations, but in that case, you need take care about compatibility yourself. This is exactly what happened in the code snippet above.The android developers example of loading bitmaps efficiently uses a custom asynctask (copied from jellybean) so you can use the executeOnExecutor in apis lower than < 11
http://developer.android.com/training/displaying-bitmaps/index.html
Download the code and go to util package.