使用进度对话框下载文件,取消下载(安卓)



下载文件时,我向用户显示此对话框,具有取消按钮

    protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading ..");
        mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                "Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }
}

我的下载代码是:

protected String doInBackground(String... aurl) {
        int count;
        try {
            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(sunDir.getPath()
                    + musicFileName);
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
        }
        return null;
    }

我的问题是:

  • 在对话框文件下载上按取消按钮时不要取消
  • 我想当用户按取消按钮时,如果文件下载完成
    或不完全删除文件

在对话框文件下载上按取消按钮时不要取消

您需要使用 AsyncTask.cancel() 在单击取消按钮时取消 AsyncTask,如下所示:

   public static boolean downloadstatus=true;
    mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                    "Cancel", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            your_AsyncTask.cancel(true);  //<<<<<
                             downloadstatus=false;
                            dialog.cancel();
                        }
                    });
如果用户下载完成

或文件下载完成,我想当用户按取消按钮时 不完全删除文件

您需要检查 AsyncTask 是否在 doInBackground 中运行或取消以停止文件下载,如下所示:

    while ((count = input.read(data)) != -1) {
       if(!your_AsyncTask.isCancelled() &&  downloadstatus !=false){
        total += count;
        publishProgress("" + (int) ((total * 100) / lenghtOfFile));
        output.write(data, 0, count);
       }
      else{
             // free all resources here
            break;
        }
    }

最新更新