从AsyncTask ProgressDialog取消AsyncTask

时间:2017-02-12 07:41:57

标签: java android android-studio android-asynctask

(这不是关于nullpointer): 我在AsyncTask中有一个进度条,我添加了一个取消按钮来取消asynctask。

我可以从asynctask外部取消asynctask,但我需要在progressdialog中实现取消函数,这是在asynctask下实现的。

所以问题是如何在asynctask下的progressdialog中实现取消按钮取消asynctask?

请检查“doInBackground”.. asynctask没有取消

Download_result.java类:

public class Download_result extends AsyncTask<String,Integer,Void>{
ProgressDialog progressDialog;
Context context;
String pdfFile;


Download_result(Context context, String pdfFile){
    this.context=context;
    this.pdfFile=pdfFile;
}
@Override
protected void onPreExecute() {
        progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("Downloading...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(200);
        progressDialog.setCancelable(false);
        progressDialog.setProgress(0);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Download_result.this.cancel(true);  
                dialog.dismiss();
            }
        });
        progressDialog.show();
}

@Override
protected Void doInBackground(String... params) {
      //given below
}
@Override
protected void onProgressUpdate(Integer... values) {
        progressDialog.setProgress(values[0]);       
}

@Override
protected void onPostExecute(Void result) {
        progressDialog.cancel();        

}
}

enter image description here

我的“doInBackground”方法:

@Override
    protected Void doInBackground(String... params) {      

            String url_1=params[0];
            int file_length=0;
            try {
                URL url = new URL(url_1);
                URLConnection urlConnection = url.openConnection();
                urlConnection.connect();
                file_length=urlConnection.getContentLength();
                filesize=file_length;
                File sdCard = Environment.getExternalStorageDirectory();
                File new_folder = new File (sdCard.getAbsolutePath() + "/xxx");


                File input_file = new File(new_folder,pdfFile);
                InputStream inputStream = new BufferedInputStream(url.openStream(),8192);
                byte[] data=new byte[1024];
                int total=0,count=0;
                OutputStream outputStream = new FileOutputStream(input_file);
                while ((count=inputStream.read(data))!=-1){
                    total+=count;
                    outputStream.write(data,0,count);


                    int progress= (total*200)/file_length;
                    downloadedsize=total;

                    publishProgress(progress);
                    if(isCancelled()){
                        break;  or return null; // same result
                    }


                }
                inputStream.close();
                outputStream.close();


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }           
        return null;//"Download completed!";
    }

4 个答案:

答案 0 :(得分:2)

您没有在取消按钮按下时取消对话框..也可以使用setButton代替

试试这个:

 @Override
protected void onPreExecute() {
        progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("Downloading...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(200);
        progressDialog.setCancelable(false);
        progressDialog.setProgress(0);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          download.cancel(true);
           downloadstatus=false;  //add boolean check
          dialog.dismiss();
        }
      });
        progressDialog.show();
}

要取消异步任务,请使用:

 Public Download_result download;
 download = new Download_result();
 download.execute();
download.cancel(true);

doInbackGround()

中试试
 while ((count=inputStream.read(data))!=-1){

                if(!your_AsyncTask.isCancelled() ||  downloadstatus !=false){
                    total+=count;
                    outputStream.write(data,0,count);
                    int progress= (total*200)/file_length;
                    downloadedsize=total;

                    publishProgress(progress);
                }else{
                    break;
                }
            }

答案 1 :(得分:1)

Download_result(Context context, String pdfFile,Download_result download)

Download_result作为参数发送到自己的构造函数没有任何意义。您永远不能有一个有效的引用来传递构造函数。您应该将此构造函数更改为

Download_result(Context context, String pdfFile)

Download_result的每个方法都已引用名为Download_result的{​​{1}}对象。由于您需要在内部类中访问它,因此请使用this

Download_result.this

答案 2 :(得分:0)

创建一个&#34; boolean keepGoing&#34;在您的AsyncTask中并将其设置为true。在你的&#34; doInBackground&#34;程序定期轮询并返回,如果错误。将取消按钮绑定到AsyncTask中的setter,该setter设置&#34; keepGoing&#34;标志为假。那应该可以胜任。

答案 3 :(得分:0)

在ProgressDialog的按钮上使用DialogInterface侦听器,例如:

protected void onPreExecute() {
            pd = new ProgressDialog(MainActivity.this);
            pd.setTitle("PAUL app");
            pd.setMessage("Loading data ...");
            pd.setButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // User has cancelled task ... just quit!
                    MainActivity.this.finish();
                    return;
                }
            });
            pd.show();
        }