running parallel AsyncTask

2019-01-04 11:22发布

I have a SplashActivity in my application which do some stuff using AsyncTask when I start my application.

I have also created another AsyncTask which downloads data from the server. Now after I close my application the AsyncTask is still downloading the data.

But when I again start my application my SplashActivity's AsyncTask does not execute its background (doInBackground function) till my downloader AsyncTask is finished, and my application is hanged.

So my question is it that we cant run two AsyncTask parallel? Both AsyncTask are different and doing their own stuff. Is there a way to do it.

3条回答
姐就是有狂的资本
2楼-- · 2019-01-04 11:54

Another option is using AsyncTaskCompat from support v.4 library.

AsyncTaskCompat.executeParallel(new AsyncTask<Void, Void, Object>() {
    @Override
    protected Object doInBackground(Void... params) {
        // do your parallel task here
        return null;
    }

    @Override
    protected void onPostExecute(Object result) {
        // and fetch result
    }
});
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-04 12:03

There has been a change in AsyncTask from Honeycomb release. Older versions had a Thread pool of 10 threads, so you could run 10 tasks in parallel. But for Honeycomb and up, default is a serial executor, which executes tasks one by one. But you can pass a ThreadPoolExecutor for execution:

   if (Build.VERSION.SDK_INT >= 11) {
     //--post GB use serial executor by default --
     task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
   } else {
     //--GB uses ThreadPoolExecutor by default--
     task.execute();
   }
查看更多
女痞
4楼-- · 2019-01-04 12:18

You will need to use a thread pool Executor to execute AsyncTask. Default implementation uses a serial executor running on a single thread

So create a ThreadPoolExecutor and then use

AsyncTask's executeOnExecutor instead of just execute method

查看更多
登录 后发表回答