如何在一个活动中运行两个AsyncTask?

问题描述 投票:7回答:4

我有两个ActivitymainActivitydownloadActivity),而我在AsyncTask中有两个downloadActivity

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
    }
}

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

android android-asynctask
4个回答
16
投票

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

请注意,两个线程不要在同一数据上交互,这可能会导致一些奇怪且难以跟踪的错误。


0
投票

您可以在具有两个方法的一个asynk类中创建它,首先在doInBackground中获取json文件等待响应...如果可以,请调用下载文件方法。这些方法将返回httpResponse对象


0
投票

您可以在活动中覆盖onBackPressed函数并完成当前活动,然后再转到上一个活动。当您再次下载downloadActivity时,它将调用它的oncreate方法并首先调用AsynctTask。


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();
                }
            } 
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.