Disable use of AsyncTask, using custom AsyncTask

假装没事ソ 提交于 2019-12-23 04:34:48

问题


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?


回答1:


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:)




回答2:


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.



来源:https://stackoverflow.com/questions/11229734/disable-use-of-asynctask-using-custom-asynctask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!