我看过这个答案:由于 AsyncTask 是一个单独的类,如何将 OnPostExecute() 的结果获取到主活动? https://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a
但这不是我要问的,因为我的调用类有多个调用AsyncTask
.
我想创建一个通用的AsyncTask
类将接受 URL 并从给定 URL 下载内容并返回下载的内容。
Example:
public class MyAsyncTask extends AsyncTask<String, Void, String>{
ProgressDialog dialog;
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "Loading", "Please wait...", true);
}
protected String doInBackground(String... params) {
// do download here
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
}
}
我还有另一个班级称之为AsyncTask
在不同场景下
public class MyClass {
public method1(String url) {
String result = new MyAsyncTask().execute(url).get();
}
public method2(String url) {
String result = new MyAsyncTask().execute(url).get();
}
}
我知道使用get()
方法将使整个过程成为同步任务。但我想将结果返回给调用类。我也知道,为了防止这种情况,我必须实现一个接口。但由于我在同一个班级中有多个电话,这是不可能的。那么有人可以给我一个解决这个问题的想法吗?