是否可以同时运行多个AsyncTask? [英] Is it possible to run multiple AsyncTask in same time?

查看:306
本文介绍了是否可以同时运行多个AsyncTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有两项活动.在我的活动A中,我使用一个AsyncTask,第二个活动B中也使用另一个AsyncTask.在活动A中,我已将一些数据上传到服务器,在活动B中,我正在尝试从服务器下载其他数据.这两个都在AsyncTask中运行.我的问题是,当我尝试从活动B中的服务器下载数据时,调用了onPreExecute()方法,但未调用doInBackground()方法,它正在等待第一个活动A的doInBackground()操作完成.为什么会这样呢?是否可以同时运行多个后台操作.

I've two activities in my application. In my Activity A I'm using one AsyncTask and second Activity B also using another one AsyncTask. In my Activity A I've upload some data to server and in my Activity B I'm trying to download some other data from server. Both these are running in AsyncTask. My problem is when I trying to download data from server in Activity B onPreExecute() method was called but doInBackground() method was not called it is waiting up to the first Activity A's doInBackground() action finished. Why it is happened? Is it possible to run more than one background actions at a same time..

活动A

ImageButton submit_button = (ImageButton) findViewById(R.id.submit_button);

submit_button.setOnClickListener(new OnClickListener() 
    {
        public void onClick(View record_button) 
        {
                       new Save_data().execute();
        }
       });
class Save_data extends AsyncTask<String, Integer, Integer> 
 {
    protected void onPreExecute() 
    {

}
    protected Integer doInBackground(String... arg0) 
{
     //uploading data here
    }

 }

在我的活动B中

ImageButton get_button = (ImageButton) findViewById(R.id.get_button);
    get_button.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View record_button) 
            {
                           new download_process().execute();
            }
           });
    class download_process extends AsyncTask<String, integer, integer>
     {
        protected void onPreExecute() 
        {
       Log.e("pre-execute","has been called");//This Log works well
    }
         protected Integer doInBackground(String... arg0) 
    {
         //downloading data here
        }   
     }

推荐答案

按如下所示使用执行程序

use executor as follows

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    new Save_data().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, location);
} else {
    new Save_data().execute(location);
}

请参见

这篇关于是否可以同时运行多个AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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