如何在一个 Activity 中运行两个 AsyncTask? [英] How run two AsyncTasks in one Activity?

查看:13
本文介绍了如何在一个 Activity 中运行两个 AsyncTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Activity (mainActivity & downloadActivity) 并且我在 AsyncTask 中有 2 个 AsyncTask代码>下载活动

I have two Activitys (mainActivity & downloadActivity) and I have 2 AsyncTasks in downloadActivity

downloadActivity 中,它首先执行 getFileAsyncTask 以读取用于添加一些图像的 JSON 文件并从图像创建一个 ListView,如果用户点击一个图像,downloadAsyncTask 被调用,它开始从互联网下载一些东西.我的问题是:当第二个 AsyncTask 运行时,我回到 mainActivity 并再次回到 downloadActivity 第一个 AsyncTask 直到 downloadAsyncTask 完成后才被调用.

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 中运行两个 AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆