如何在一个Activity中运行两个AsyncTasks?

6
我有两个Activity(mainActivity和downloadActivity),在downloadActivity中有两个AsyncTask。
在downloadActivity中,首先执行getFileAsyncTask来读取JSON文件以添加一些图像,并从这些图像创建一个ListView。如果用户点击图像,则会调用downloadAsyncTask并开始从互联网下载某些内容。
我的问题在于:当第二个AsyncTask正在运行时,我回到mainActivity再返回downloadActivity时,第一个AsyncTask不会被调用,直到downloadAsyncTask完成。
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
    }
}

注意: 我想写一些类似购物应用程序的东西。例如,用户可以下载文件并浏览商店以查看产品。

4个回答

15

如果您想并行运行多个AsyncTasks,则可以在任务上调用executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)而不是execute()。默认情况下,AsyncTasks以串行方式运行,先到先得。

要注意的是,两个线程不要对同一数据进行交互,否则可能会导致一些奇怪且难以跟踪的错误。


0
创建一个类任务,如下:
在主线程中全局声明进度条。
现在你需要在主线程中启动一个异步任务,如下:
public class myactivity extends Activity {
    private ProgressDialog _dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_screen);
        new abc().execute();
    }

    class abc extends AsyncTask(String,String,String) {
        @Override
        protected void onPreExecute() {
            _dialog = new ProgressDialog(_ctx);
            _dialog.setCancelable(false);
            _dialog.setMessage("Loading");
            _dialog.show();
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            @Override
            protected void onPostExecute(String result) {
                // in post execute of this class you can run a new thread of your downaloder thread. and in post execute of last thread you have to dismiss the progess bar.
                new download activity.execute();
                }
            } 
        }
    }
}

0

你可以在一个异步类中实现它,该类有两个方法。第一个方法获取JSON文件并等待在doInBackground中的响应……如果一切正常,则调用下载文件方法。这些方法将返回一个httpResponse对象。


0

您可以在活动中重写onBackPressed函数,在返回上一个活动之前完成当前活动。当再次进入downloadActivity时,它会调用其oncreate方法并调用第一个AsynctTask。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接