Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

android - Is it possible to run multiple AsyncTask in same time?

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

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

 }

In my Activity 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
        }   
     }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

See this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...