【问题标题】:Constructor in an Anonymous AsyncTask like this "new AsyncTask<Exercise,Void,Void>()"?匿名 AsyncTask 中的构造函数,例如“new AsyncTask<Exercise,Void,Void>()”?
【发布时间】:2020-12-16 11:26:33
【问题描述】:

将每项工作都放在我的代码中某处的 AsyncTask 类中对我来说真的很痛苦,但代码没有执行,我希望他执行。

我曾经使用new AsyncTask&lt;Void, Void, Void&gt;(){} 函数将代码放在我期望的位置,这对每个人都适用。

如果我想将 AsyncTask 与父类中的变量一起使用,它当然会警告我可能存在内存泄漏。

有没有办法在这个匿名 AsyncTask 中有一个构造函数?我认为没有,但如果有办法将代码保持在原位,但将变量传递到异步任务中,那就太好了。

可能是这样的:

        AsyncTask<Exercise, Void, Void> insert = new AsyncTask <Exercise, Void, Void>(){
            private Exercise mExercise;
            
            public AsyncTask(Exercise exercise){
                mExercise = exercise;
            }
            
            @Override
            protected Void doInBackground(Exercise... exercises) {
                mExerciseDAO.insertExercise(exercises[0]);
                return null;
            }

        };

【问题讨论】:

    标签: java android constructor android-asynctask anonymous-function


    【解决方案1】:

    以下是将您的练习参数传递给匿名 AsyncTask 的方法:

    new AsyncTask<Void,Void,Void>(){
    
        Exercise mExercise;
    
        @Override
        protected Void doInBackground(Void... params) {
    
            // Your code ...
            mExerciseDAO.insertExercise(this.mExercise);
            return null;
        }
    
        public AsyncTask setExercise (Exercise exercise){
            this.mExercise = exercise;
            return this;
        }
    
    }.setExercise(exercise).execute();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      相关资源
      最近更新 更多