Android AsyncTask as method argument
android, android-asynctask, parameters
Solution
Since `AsyncTask` is a parameterized class, you need to use generics. Something like this:
@SuppressLint("NewApi")
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);
}
}
Use like this:
MyAsyncTask task = new MyAsyncTask();
Utils.execute(task);
Problem
I'm working on an app which uses a lot of AsyncTasks. When I started to participate at coding of this app the targetSdkVersion was set to 10 so we hadn't problems with the AsyncTasks because they are all executed on parallel background threads. Since we have set the targtSdkVersion to 17 we've got some problems with the tasks because they are now executed on a single background thread. To solve this problem I've found the following code to specifically use parallel tasks: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { myTask.execute(); } ``` Now, because we have several tasks needing these lines of code, I would like to write a method in our own Utils class which executes the tasks in this manner... but I can't achieve this, because I can't pass the different tasks to the method as argument due the 'Param | Progress | Result' stuff differs from one task to another. Is there a way to achieve our goal? Any ideas?