Android how to implement parallel execution for As

2020-07-21 05:54发布

问题:

I need to allow multiple AsyncTask to be running at the same time . This my my AsyncTask :

 private void callAPI(String user_id) {
    new AsyncTask<Void, Void, String>() {

            protected String doInBackground(Void... parameters) {



                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("user_id",    user_id));

                return api.post("", params);


            }//end doInBackground


            protected void onPostExecute(String result) {
                Log.i(TAG + "POST() => " + result);


            }//end onPostExecute
        }.execute(); //end AsyncTask
      }

I saw an answer at running-multiple-asynctasks but I don't know how to use it . How can I implement the code below within my AsyncTask :

     @TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
void startMyTask(AsyncTask asyncTask) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    else
        asyncTask.execute(params);
}

回答1:

Create call from AsynTask and call class from MainActivity synchronously :

public class ApiCalling extends AsyncTask<String, Void, String>() {

        protected String doInBackground(String... parameters) {

            Log.d("LogTag","starting Async Task:"+parameters[0]);

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user_id",    user_id));

            return api.post("", params);


        }//end doInBackground


        protected void onPostExecute(String result) {
            Log.i(TAG + "POST() => " + result);


        }//end onPostExecute
    }.execute(); //end AsyncTask

From your MainActivity onCreate():

ApiCalling mObj = new ApiCalling();
mObj.execute("call 1");


 /* if the task inside asyn task if long, then better to get new reference of Async task and execute other task */
ApiCalling mObj = new ApiCalling();
mObj.execute("call 2");


回答2:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;

/**
 * An executor for concurrently executing AsyncTask tasks
 * It takes all work for understanding device`s Android version 
 * and executes your AsyncTasks tasks concurrently
 * @author Artem Zinnatullin (artem.zinnatullin@gmail.com)
 * @version 1.2
 */
public class AsyncTaskExecutor {

    private static final int CORE_POOL_SIZE;
    private static final int MAXIMUM_POOL_SIZE;
    private static final int KEEP_ALIVE;
    private static final TimeUnit TIME_UNIT;

    private static final BlockingQueue<Runnable> concurrentPoolWorkQueue;
    private static final ThreadFactory concurrentThreadFactory;
    private static final ThreadPoolExecutor concurrentExecutor;

    private AsyncTaskExecutor() {}

    static {
        CORE_POOL_SIZE    = 5;
        MAXIMUM_POOL_SIZE = 128;
        KEEP_ALIVE        = 1;
        TIME_UNIT         = TimeUnit.SECONDS;

        concurrentPoolWorkQueue = new LinkedBlockingQueue<Runnable>(10);
        concurrentThreadFactory = new AsyncTaskThreadFactory();
        concurrentExecutor      = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAXIMUM_POOL_SIZE,
                KEEP_ALIVE,
                TIME_UNIT,
                concurrentPoolWorkQueue,
                concurrentThreadFactory
        );
    }

    /**
     * Concurrently executes AsyncTask on any Android version
     * @param task to execute
     * @param params for task
     * @return executing AsyncTask 
     */
    @SuppressLint("NewApi") 
    public static <Params, Progress, Result> AsyncTask<Params, Progress, Result> 
        executeConcurrently(AsyncTask<Params, Progress, Result> task, Params... params) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            task.executeOnExecutor(concurrentExecutor, params);
        } else {
            task.execute(params);
        }

        return task;
    }

    /**
     * Thread factory for AsyncTaskExecutor
     * @author Artem Zinnatullin
     */
    private static class AsyncTaskThreadFactory implements ThreadFactory {
        private final AtomicInteger count = new AtomicInteger(1);;

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + count.getAndIncrement());
        }
    }
}

Use this class if you want to execute concurrently Asynctask. Found this class and its working for me.

AsyncTaskExecutor.executeConcurrently(new YourAsyncTask(),1);

Asynctask

private class YourAsyncTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(mContext, "Please wait..Fetching Data",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(Integer... params) {
            Log.e("passing value",""+params[0]);
            String uri = "http://abcd.com/ServiceTest.php?id="
                    + params[0];
            Log.e("passing value",""+uri);
            return SetServerString;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(SetServerString);

    }

Hope it helps you!