首页 > 解决方案 > 在其他类中获取 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但是即使文件存在于服务器上,这段代码也不是我通过“报告尚未准备好”按钮获得的工作时间。

谢谢你。

标签: javaandroidandroid-asynctaskandroid-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);

推荐阅读