KinGPinG
KinGPinG

Reputation: 171

Generic AsyncTask to be used on any android version

I'm making an android app "compatible" to any version of Android from 2.3 to 4... What I'm trying to accomplish is make a generic class which extends from AsyncTask and can be used to process in background different tasks. I've been reading and found a work around like this:

AsyncTask task = new YourTask();
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
    task.execute(params);
} else {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); 
}

I just don't want to do this every single time I need to use an AsyncTask just to use .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) I SHOULD USE executeOnExecutor for better performance on anything that supports it instead of execute();

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {

                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected Void doInBackground(Void... params) {
                            // Any task
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            super.onPostExecute(aVoid);
                        }
                    }.execute();

                } else {

                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected Void doInBackground(Void... params) {
                            //Any task
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            super.onPostExecute(aVoid);

                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);//This is the different thing.

                }

The problem is that no all the tasks are the same so parameters change as well as the result of those tasks. Has someone faced the same problem? Any recomendation?

Thanks in advance.

Upvotes: 0

Views: 341

Answers (1)

Dan Harms
Dan Harms

Reputation: 4840

Add the logic to an overridden execute() method. Then just call YourTask.execute().

public final AsyncTask<Params, Progress, Result> execute(Params... params) {
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
        super.execute(params);
    } else {
        super.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    }
}

Upvotes: 1

Related Questions