如何在一个Activity中运行两个AsyncTasks? [英] How run two AsyncTasks in one Activity?
问题描述
我有两个Activity
(mainActivity
& downloadActivity
),而我在downloadActivity
中有2个AsyncTask
I have two Activity
s (mainActivity
& downloadActivity
) and I have 2 AsyncTask
s in downloadActivity
在downloadActivity
中,它首先执行getFileAsyncTask
以读取JSON文件以添加一些图像并从图像中创建ListView
,如果用户单击图像,则会调用downloadAsyncTask
并开始下载内容来自网络.
我的问题在这里:当第二个AsyncTask
运行时,我回到mainActivity
并再次返回到downloadActivity
,直到downloadAsyncTask
完成时才调用第一个AsyncTask
.
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 .
推荐答案
如果要并行运行多个AsyncTasks
,则可以在任务上调用executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
而不是execute()
.默认情况下,AsyncTasks
以串行方式运行,先到先得.
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.
这篇关于如何在一个Activity中运行两个AsyncTasks?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!