Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AsyncTask as method argument

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?

like image 415
tobi_b Avatar asked Apr 18 '13 08:04

tobi_b


People also ask

What can I use instead of AsyncTask?

Use the standard java. util. concurrent or Kotlin concurrency utilities instead.

What is the use of AsyncTask in Android?

Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.

What method must be overridden when using AsyncTask to execute statements on a separate thread?

In Android, AsyncTask (Asynchronous Task) allows us to run the instruction in the background and then synchronize again with our main thread. This class will override at least one method i.e doInBackground(Params) and most often will override second method onPostExecute(Result).

What is difference between service thread and AsyncTask?

service is like activity long time consuming task but Async task allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.


1 Answers

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);
like image 139
Nikolay Elenkov Avatar answered Sep 30 '22 19:09

Nikolay Elenkov