I am not sure if this is possible or if I am thinking of this correctly.
In the Android developer training for Displaying Bitmaps Efficiently, a custom version of the AsyncTask
is used to make the code compatible with android versions below HONEYCOMB
.
This great answer explains the differences between AsyncTask
operation in pre and post HONEYCOMB
. The reason that a custom version is supplied in the guide is that the default in pre HONEYCOMB
(a pool of tasks) will very easily crash with a java.util.concurrent.RejectedExecutionException
if the GridView
of images is scrolled quickly. For this scenario, the default post HONEYCOMB
version (serial execution on an additional thread) is what is required.
I could easily do this by using a newer version of AsyncTask
in my project (like done in the developer training example) but this is not very compatible with future changes.
What I would like to do is the following:
If the version is
HONEYCOMB
or greater, use the implementation ofAsyncTask
provided in the framework, whereas if it is earlier, use theAsyncTask
implementation provided in my application.
Is this possible (and how) or should I be thinking about it differently?
EDIT:
I understand how to provide conditionals based on the running SDK_VERSION
.
The issue I have is that AsyncTask
is an abstract class, meaning that I have to provide an implementation.
E.g. I have a AsyncTask
called myTask
which extends AsyncTask
like below:
public class myTask extends AsyncTask<Void, Void, Void> {
// Implementations for the abstract functions (doInBackground)
}
How do I decide which version of the AsyncTask
is extended?
You can do something like:
if(android.os.Build.VERSION.SDK_INT >= 11){ // Honeycomb
{
AsyncTask taskObj = new DefaultAsyncTaskImpl();
taskObj.execute();
} else {
AsyncTask taskObj = new CustomAsyncTaskImpl();
taskObj.execute();
}
And in your code define both classes in which the first extends AsyncTask
and the second is your own implementation
Note: SDK_INT
available in API 4+
Edit:
You can use factory design pattern
to decide which object to create based on the SDK version.