Search code examples
androidandroid-asynctaskcompatibility

AsyncTask Thread_Pool_Executor on Android API <11


Im trying to allow my app to run on older versions of Android, Specifically API 10.

I've downloaded the support packages and used them to solve a few problems but im struggling to fix this one:

Field requires API level 11 (current min is 10): android.os.AsyncTask#THREAD_POOL_EXECUTOR

The Thread_Pool_Executor method was only added in API 11.

Is there any way i can use this in API 10 or do i have to revert back to:

myAsyncTask().execute();

instead of:

myAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

If so how do i check the API level?


Solution

  • Step #1: Set your build target (e.g., Project > Properties > Android in Eclipse) to API Level 11 or higher.

    Step #2: Use Build.VERSION.SDK_INT to determine your API level, to use executeOnExecutor() only on newer Android devices.

    For example, you could have this static utility method somewhere:

      @TargetApi(Build.VERSION_CODES.HONEYCOMB)
      static public <T> void executeAsyncTask(AsyncTask<T, ?, ?> task, T... params) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
          task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
        }
        else {
          task.execute(params);
        }
      }
    

    Then, to execute a task, just call executeAsyncTask(), passing it your AsyncTask instance and whatever parameters you want passed into your doInBackground() method. executeAsyncTask() will choose executeOnExecutor() on API Level 11+ or use execute() on older devices.