我需要允许多个AsyncTask同时运行。 这是我的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
}
我在running-multiple-asynctasks看到了答案,但我不知道如何使用它。 如何在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);
}
答案 0 :(得分: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());
}
}
}
如果要同时执行Asynctask,请使用此类。找到这个课程,它为我工作。
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);
}
希望它可以帮到你!
答案 1 :(得分:2)
从AsynTask创建调用并同步调用MainActivity中的类:
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
来自您的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");