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?
Use the standard java. util. concurrent or Kotlin concurrency utilities instead.
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.
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).
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With