是否可以同时运行多个AsyncTask?

时间:2013-08-21 12:37:53

标签: android

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

在活动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
        }   
     }

2 个答案:

答案 0 :(得分:25)

使用执行程序如下

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

请参阅this

答案 1 :(得分:16)

是的,确实如此,但自从Honeycomb以来,Android上处理AsyncTask的方式发生了变化。从HC +开始,它们按顺序执行,而不是像过去那样并行执行。解决方案是像这样调用它们(将它放在单独的工具类中):

public class AsyncTaskTools {
    public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task) {
        execute(task, (P[]) null);
    }

    @SuppressLint("NewApi")
    public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task, P... params) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
        } else {
            task.execute(params);
        }
    }
}

然后你可以简单地打电话:

AsyncTaskTools.execute( new MyAsyncTask() );

或使用params(但我更喜欢通过任务构造函数建议passign params):

AsyncTaskTools.execute( new MyAsyncTask(), <your params here> );
相关问题