java - 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);
}
}
解决方案
当您使用以下代码声明接口时:
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.
}
};
推荐阅读
- javascript - WebSocket 连接到“wss://hostname/”失败:
- php - 自定义 wordpress 插件-首页中的 table 标签替换为 p 标签
- google-cloud-platform - GCP 工作流程:附加到数组
- xml - Unity GrammarRecognizer 和 XML 文件问题。在 Unity 中无法识别任何内容
- office-js - Office.Body.setAsync 的行为不一致
- reactjs - 未找到反应 url 的 Spring Boot 问题
- html - 如果我的 observable 是一个数组,我将如何从组件的 html 部分中的 angular observable 获取单个数据?
- azure - 在复制数据接收器参数中动态输入文件路径时出错 - ADF
- javascript - Glob 模式忽略某些 .dot.js 文件
- python - 如何从 url 列表中提取文本并分别保存