Is it possible to run multiple AsyncTask in same time?

前端 未结 2 647
遇见更好的自我
遇见更好的自我 2020-12-01 14:47

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

相关标签:
2条回答
  • 2020-12-01 15:17

    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

    0 讨论(0)
  • 2020-12-01 15:29

    Yes, it is, but since Honeycomb, there's a change in the way AsyncTask is handled on Android. From HC+ they are executed sequentially, instead of being fired in parallel, as it used to be. Solution for this is to run AsyncTask using THREAD_POOL_EXECUTOR executor explicitely. You can create helper class for that:

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

    and then you can simply call:

    AsyncTaskTools.execute( new MyAsyncTask() );
    

    or with params (however I rather suggest passign params via task constructor):

    AsyncTaskTools.execute( new MyAsyncTask(), <your params here> );
    
    0 讨论(0)
提交回复
热议问题