首页 > 解决方案 > Android Java 无法调用 ASyncTask

问题描述

我是 android 和 java 编程的新手,但我被赋予了完成承包商启动的应用程序的任务。我查找并找到了如何调用异步任务并等待它完成但我无法让它工作。事实上,它甚至不会编译。我从如何将 OnPostExecute() 的结果复制到主要活动中的答案之一,因为 AsyncTask 是一个单独的类?

我得到的错误如下。他们进入 MyCalling 课程。我将 ***** 附加到有错误的行的末尾

错误:

   processFinish(String) in <anonymous 
   com.zoeller.z_controlmobile.MyCallingClass$2> cannot implement 
   processFinish(String) in AsyncResponse
   attempting to assign weaker access privileges; was public

   error: incompatible types: AsyncTask<String,String,String> cannot be 
   converted to MyASyncClass

我的代码如下

public class MyCallingClass extends ActivityBase {
    private String _result = null;

    protected void onCreate(Bundle savedInstanceState) {
        callingMethod();
    }

    protected void callingMethod() {
        MyASyncClass whatever = new MyASyncClass(new MyASyncClass.AsyncResponse() {
            @Override
            void processFinish(String output) { *****
                _result = output;
            }
        }).execute();
    }

    // More work done here
}

public class MyASyncClass extends AsyncTask<String, String, String> {
    public interface AsyncResponse {
        void processFinish(String output);
    }

    public AsyncResponse delegate = null;

    public DeviceConnect(AsyncResponse delegate){
        this.delegate = delegate;
    }

    @Override    
    protected String doInBackground(String... params) {
    // Does the work
    }

    @Override
    public void onPostExecute(String result) {
        delegate.processFinish(result);
    }
}

标签: javaandroidandroid-asynctask

解决方案


当您使用以下代码声明接口时:

public class MyASyncClass extends AsyncTask<String, String, String> {

    public interface AsyncResponse {
        void processFinish(String output);
    }

     ...
}

访问修饰符void processFinish(String output)隐式分配给public。所以,你真正得到的是:

public class MyASyncClass extends AsyncTask<String, String, String> {

    public interface AsyncResponse {
        public void processFinish(String output);
    }

    ...
}

当你从接口构造一个对象时,你需要重写方法和访问修饰符。像这样的东西:

MyASyncClass.AsyncResponse response = new MyASyncClass.AsyncResponse() {
        @Override
        public void processFinish(String output) {
           // do something with the output.
        }
    };

推荐阅读