Skip to content

Instantly share code, notes, and snippets.

@greenrobot
Created May 23, 2012 08:26
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save greenrobot/2773896 to your computer and use it in GitHub Desktop.
Save greenrobot/2773896 to your computer and use it in GitHub Desktop.
Helper bringing back parallel execution for AsyncTask (you are no serial execution and pseudo threading wimp, right?). Uses level 11 APIs when possible.
package de.greenrobot.util;
import java.util.concurrent.Executor;
import android.os.AsyncTask;
import android.os.Build;
/**
* Uses level 11 APIs when possible to use parallel/serial executors and falls back to standard execution if API level
* is below 11.
*
* @author Markus
*/
public class AsyncTaskExecutionHelper {
static class HoneycombExecutionHelper {
public static <P> void execute(AsyncTask<P, ?, ?> asyncTask, boolean parallel, P... params) {
Executor executor = parallel ? AsyncTask.THREAD_POOL_EXECUTOR : AsyncTask.SERIAL_EXECUTOR;
asyncTask.executeOnExecutor(executor, params);
}
}
public static <P> void executeParallel(AsyncTask<P, ?, ?> asyncTask, P... params) {
execute(asyncTask, true, params);
}
public static <P> void executeSerial(AsyncTask<P, ?, ?> asyncTask, P... params) {
execute(asyncTask, false, params);
}
private static <P> void execute(AsyncTask<P, ?, ?> asyncTask, boolean parallel, P... params) {
if (Build.VERSION.SDK_INT >= 11) {
HoneycombExecutionHelper.execute(asyncTask, parallel, params);
} else {
asyncTask.execute(params);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment