java - 使 onPreExecute 和 onProgressUpdate 对所有 Asynctask 类通用

标签 java android android-asynctask

目前,我正在 android 应用程序中工作,因为我有 10 个单独的 Asynctask 类用于 10 个单独的操作,其中 onPreExecute() 和 onProgressUpdate() 内部调用的用户定义函数对于所有 10 个 Asynctask 类都是相同的。有没有其他方法可以简化这个。例如,我有一个名为“ADD”的用户定义函数,到目前为止,我已经在所有 10 个 Asynctask 类的 onPreExecute() 中调用了“ADD”函数,是否有其他方法可以通过使用接口(interface)或其他任何其他,

最佳答案

创建一个类 BaseAsyncTask,它扩展了 AsyncTask。 并编写 onPreExecute() 和 onProgressUpdate() int this 的实现。

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

        @android.support.annotation.Nullable
        private ProgressDialog progressDialog = null;
        public Activity activity;

        public BaseAsyncTask(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(activity, R.style.CustomProgressSpinner);
            CommonUtilities.showDialog(progressDialog,activity);
        }

    @Override
    protected void onProgressUpdate(Progress... values) {
        super.onProgressUpdate(values);
    }

        @Override
        protected void onPostExecute(Result result) {
            super.onPostExecute(result);
            CommonUtilities.dismissDialog(progressDialog);
        }
    }

并在所有 AsyncTask 中扩展该 BaseAsyncTask。

public class AttachmentLoadTask extends BaseAsyncTask<DocumentVO, Void, File> {@Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected File doInBackground(DocumentVO... documentVOs) {
        File file = null;
        return file;
    }

    @Override
    protected void onProgressUpdate(Progress... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(File file) {

        super.onPostExecute(file);

    }}

关于java - 使 onPreExecute 和 onProgressUpdate 对所有 Asynctask 类通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41344079/

相关文章:

java - Spring - 在运行时使用自定义限定符获取 bean

java - 如何从枚举中获取字段

java - Junit5 从 @MethodSource 注解返回 Map

java - 如何更改按钮的 onClick() 行为?

android - 安排发布到 Google Play Android Market

java - android - 回收适配器未出现在 View 寻呼机中

android - 主要 Activity 中的异步任务如何显示进度对话框

java - 邮件程序插件抛出 NullPointerException

android - ListView 中的项目看起来不像我的项目布局

android - 从 AsyncTask 类收集值卡住了我的 UI