Android AsyncTask as a method argument

I am working on an application that uses a lot of AsyncTasks. When I started participating in the coding of this application, targetSdkVersion was set to 10, so we had no problems with AsyncTasks, because they all ran on parallel background threads. Since we set targtSdkVersion to 17, we have some problems with tasks because they are now running on the same background thread. To solve this problem, I found the following code for the specific use of parallel tasks:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { myTask.execute(); } 

Now, since we have several tasks that require these lines of code, I would like to write a method in our own Utils class that performs tasks this way ... but I cannot achieve this because I can’t pass various tasks to the method as argument due to param | Progress | The Result material is different from one task to another. Is there a way to achieve our goal? Any ideas?

+6
source share
1 answer

Since AsyncTask is a parameterized class, you need to use generics. Something like that:

 @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 this:

 MyAsyncTask task = new MyAsyncTask(); Utils.execute(task); 
+9
source

All Articles