并行执行多个 AsyncTask [英] Executing Multiple AsyncTask's Parallely
问题描述
我使用的是 Android SDK 4.0.3 API15,我想并行运行多个 AsyncTask.我从网络服务器获取我的数据并实时动画(10 fps).但是根据用户操作,我还需要向 Web 服务器发送一些数据.发生这种情况时,我的动画会暂停一小段时间(发送数据进入队列并获取数据等待它完成),因此我无法捕捉实时.
I'm using Android SDK 4.0.3 API15 and I want to run multiple AsyncTasks parallely. I'm getting my data from web server and animating(10 fps) it real-time. But depending on user operations I need to send some data to web server also. When this occurs my animation pauses for a short time (sending data gets into queue and getting data waits it to finish ) and therefore I can't catch the real-time.
这个 answer 很好解释,但我无法让它发挥作用.所以任何帮助将不胜感激.
This answer is quite explaining but I couldn't make it work. So any help will be very appreciated.
我想我需要使用这个函数来实现:
I think I need to use this function to achieve that:
AsyncTask.executeOnExecutor(Executor exec, Params... params)
但是我无法将执行程序作为参数传递,也无法实例化执行程序.这是我的 AsyncTask 类:
But I can't pass an executor as a parameter and I can't instantiate an executor. This is my AsyncTask class:
public class GetPlayers extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
rawData="";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
if((rawData = buffer.readLine()) == null){
rawData = "error";
}
} catch (Exception e) {
e.printStackTrace();
}
}
return rawData;
}
@Override
protected void onPostExecute(String result) {
manipulate();
}
}
我是这样执行的:
GetPlayers task = new GetPlayers();
requestString = "web adress is here...";
task.execute(new String[] { requestString });
推荐答案
我就是这样做的:
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
new MyAsyncTask().execute();
}
其中 MyAsyncTask
是常规的 AsyncTask 子类.或者你可以把这一切都包装在辅助类中:
where MyAsyncTask
is regular AsyncTask subclass. Or you can wrap this all in helper class:
class TaskHelper {
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);
}
}
}
然后就这样做:
TaskHelper.execute( new MyTask() );
或
TaskHelper.execute( new MyTask(), args );
或
TaskHelper.execute( new MyTask(constructorParams), args );
这篇关于并行执行多个 AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!