java - 在其他类中获取 AsyncTask 的输出
问题描述
我正在学习android开发,我必须检查服务器上是否存在文件。
我正在使用以下代码
public class CheckReportExists extends AsyncTask<String, Void, Boolean>{
Boolean fileExists = false;
public CheckReportExists() {
}
public Boolean CheckReportExists1(String download_url){
execute(download_url);
return fileExists;
}
@Override
protected void onPreExecute() {
//display progress dialog.
}
@Override
protected Boolean doInBackground(String... params) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(params[0]).openConnection();
con.setRequestMethod("HEAD");
int response = con.getResponseCode();
if(response == HttpURLConnection.HTTP_OK){
fileExists = true;
}
} catch(Exception e){
}
return fileExists;
}
@Override
protected void onPostExecute(Boolean result) {
// dismiss progress dialog and update ui
//super.onPostExecute(result);
}
}
要调用它,我使用以下代码
CheckReportExists cre = new CheckReportExists();
Boolean fileExists = cre.CheckReportExists1(download_url);
if(fileExists) {
builder.setPositiveButton("Download Report", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new DownloadTask(Results.this, download_url);
}
});
}else{
builder.setPositiveButton("Report not ready yet", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
AlertDialog
但是即使文件存在于服务器上,这段代码也不是我通过“报告尚未准备好”按钮获得的工作时间。
谢谢你。
解决方案
像这样的东西:
CheckReportExists cre = new CheckReportExists() {
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// RIGHT HERE is where you can add your code to handle the result
}
};
// CheckReportExists1 is no longer a good name because it's not
// returning a value. It just starts the process.
cre.CheckReportExists1(download_url);
推荐阅读
- javascript - 添加更多视频
- python - Django确定Min是否唯一
- ios - CAEmitterLayer 最终在添加 EmitterCells 时有延迟
- python - 当 win.blit() 后台 pygame 时滞后
- c# - 调用在 Postman 中有效,但在 C# 中无效
- r - 在 R 中绘制回归输出时指定不同组的端点
- angular - 无法使用拦截器捕获 HTTP 错误代码
- python - 有没有办法从另一个无限行长的数据帧动态生成数据帧?
- flutter - 使用 ModalRoute Flutter 获取导航器参数,无需监听/订阅
- html - Wordpress - 如何防止从模板中删除评论