質問

I have the following implementation of AsyncTask, allowing multiple AsyncTasks to run concurrently:

public abstract class MyAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

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

Now to avoid confusion and accidental use of the normal AsyncTask, I would like to block access from my code to:

  • The AsyncTask class, only MyAsyncTask should be used.
  • The execute() function in MyAsyncTask.

Is it possible to do this?

役に立ちましたか?

解決

My idea of doing this would be a bit different. Instead of extending the AsyncTask class, you can create a method that takes as a parameter the AsyncTask you want to use. Here is an example:

public void executeAsyncTask(AsyncTask asyncTask) {

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        asyncTask.executeOnExecutor(THREAD_POOL_EXECUTOR, params);
    } else {
        asyncTask.execute(params);
    }
}

With this you just need to instantiate the AsyncTask you want to use without worrying about the problems you mentioned since you will be extending the Android's AsyncTask class having overriden the execute method the way you want. So lets say that you have defined an AsyncTask named customAsyncTask, to execute it you just call executeAsyncTask(new customAsyncTask(your_params)); You can define the above method in a static class (making the method also static) for easier access.

Hope that helps:)

他のヒント

Do not import AsyncTask and only import your MyAsyncTask class. That way your class is the only available option.

I suppose you could overwrite the AsyncTask method in your main file. You must have a new class file for your MyAsyncTask, however, or it will not inherit it correctly.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top