繁体   English   中英

从AsyncTask ProgressDialog取消AsyncTask

[英]Canceling AsyncTask from AsyncTask ProgressDialog

(这与nullpointer无关):我在AsyncTask中有一个进度条,并且添加了一个Cancel按钮来取消asynctask。

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

那么问题是如何使用在asynctask下的progressdialog中实现的cancel按钮取消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();        

}
}

在此处输入图片说明

我的“ 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!";
    }

您尚未取消按取消按钮中的对话框。也请使用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;
                }
            }
Download_result(Context context, String pdfFile,Download_result download)

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

Download_result(Context context, String pdfFile)

Download_result每个方法已经具有对名为thisDownload_result对象的引用。 由于您需要在内部类中访问它,因此请使用Download_result.this

progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        Download_result.this.cancel(true);
        dialog.dismiss();
    }
});

在AsyncTask中创建一个“ boolean keepGoing”并将其设置为true。 在您的“ doInBackground”过程中,定期对其进行轮询并返回(如果为false)。 将取消按钮绑定到AsyncTask中的设置器,该设置器将“ keepGoing”标志设置为false。 那应该做的。

在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();
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM