簡體   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