Android 如何取消从对话框下载文件

Android 如何取消从对话框下载文件,android,android-layout,dialog,Android,Android Layout,Dialog,当用户下载文件时,我向用户显示一个包含取消按钮的对话框 我的问题是,当用户按下对话框文件上的“取消”按钮时,下载过程不会被取消 我想当用户按下取消按钮文件下载完成或没有,我必须删除。 请向任何人解释我是如何做到这一点的 代码: 只需在类中添加一个布尔值,即可控制while循环。像 while (continueDownload&& (len1 = is.read(buffer)) != -1) { 让它像这样工作 yourDwnloadTask.setContinueDownl

当用户下载文件时,我向用户显示一个包含取消按钮的对话框

我的问题是,当用户按下对话框文件上的“取消”按钮时,下载过程不会被取消

我想当用户按下取消按钮文件下载完成或没有,我必须删除。 请向任何人解释我是如何做到这一点的

代码:


只需在类中添加一个布尔值,即可控制while循环。像

while (continueDownload&& (len1 = is.read(buffer)) != -1) {
让它像这样工作

yourDwnloadTask.setContinueDownload(false);
并处理输出文件

if (!continueDownload && outputFile.exists()) {
                try {
                    outputFile.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
如果你问我完整的代码

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadTask {
    private static final String TAG = "Download Task";
    private Context context;
    private String downloadUrl = "", downloadFileName = "";
    private ProgressDialog progressDialog;
    private boolean continueDownload = true;

    public void setContinueDownload(boolean continueDownload) {
        this.continueDownload = continueDownload;
    }

    public DownloadTask(Context context, String downloadUrl) {
        this.context = context;
        this.downloadUrl = downloadUrl;
        downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'), downloadUrl.length());
        continueDownload = true;
        Log.e(TAG, downloadFileName);
        //Start Downloading Task
        new DownloadingTask().execute();
    }

    private class DownloadingTask extends AsyncTask<Void, Integer, Void> {
        File apkStorage = null;
        File outputFile = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(bookejtemaeat.this);
            progressDialog.setMessage("يتم تحميل الملف مرة واحدة يرجى الانتظار ......");
            progressDialog.setIndeterminate(true);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(false);
            progressDialog.setProgress(0);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DownloadingTask.this.cancel(true);
                    dialog.dismiss();
                }
            });
            progressDialog.show();
        }


        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                URL url = new URL(downloadUrl);//Create Download URL
                HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
                c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
                c.connect();//connect the URL Connection
                final int fileLength = c.getContentLength();
                Log.e(TAG, "fileLength " + fileLength);
                if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
                            + " " + c.getResponseMessage());

                }
                //Get File if SD card is present
                if (new CheckForSDCard().isSDCardPresent()) {
                    apkStorage = getApplicationContext().getDir(
                            "NKDROID FILES", Context.MODE_PRIVATE);
                } else
                    Toast.makeText(context, "Tidak ada SD Card.", Toast.LENGTH_SHORT).show();
                //If File is not present create directory
                if (!apkStorage.exists()) {
                    apkStorage.mkdir();
                    Log.e(TAG, "Directory Created.");
                }
                outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
                //Create New File if not present
                if (!outputFile.exists()) {
                    outputFile.createNewFile();
                    Log.e(TAG, "File Created");
                }
                FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
                InputStream is = c.getInputStream();//Get InputStream for connection
                byte[] buffer = new byte[1024];//Set buffer type
                int len1 = 0;//init length
                long total = 0;
                while (continueDownload && (len1 = is.read(buffer)) != -1) {
                    total += len1;
                    final long total_tmp = total;
                    Log.e(TAG, "progressDialog " + (total * 100 / fileLength));
                    publishProgress((int) (total * 100 / fileLength));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setProgress((int) (total_tmp * 100 / fileLength));
                        }
                    });
                    fos.write(buffer, 0, len1);//Write new file
                }
                if (!continueDownload && outputFile.exists()) {
                    try {
                        outputFile.delete();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //Close all connection after doing task
                fos.close();
                is.close();
            } catch (Exception e) {
                //Read exception if something went wrong
                e.printStackTrace();
                outputFile = null;
                Log.e(TAG, "Download Error Exception " + e.getMessage());
            }
            return null;
        }
    }
}

感谢您的回复,但当我添加DownloadingTask.setContinueDownloadfalse时;你应该选择你需要停止下载的地方。
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadTask {
    private static final String TAG = "Download Task";
    private Context context;
    private String downloadUrl = "", downloadFileName = "";
    private ProgressDialog progressDialog;
    private boolean continueDownload = true;

    public void setContinueDownload(boolean continueDownload) {
        this.continueDownload = continueDownload;
    }

    public DownloadTask(Context context, String downloadUrl) {
        this.context = context;
        this.downloadUrl = downloadUrl;
        downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'), downloadUrl.length());
        continueDownload = true;
        Log.e(TAG, downloadFileName);
        //Start Downloading Task
        new DownloadingTask().execute();
    }

    private class DownloadingTask extends AsyncTask<Void, Integer, Void> {
        File apkStorage = null;
        File outputFile = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(bookejtemaeat.this);
            progressDialog.setMessage("يتم تحميل الملف مرة واحدة يرجى الانتظار ......");
            progressDialog.setIndeterminate(true);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(false);
            progressDialog.setProgress(0);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DownloadingTask.this.cancel(true);
                    dialog.dismiss();
                }
            });
            progressDialog.show();
        }


        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                URL url = new URL(downloadUrl);//Create Download URL
                HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
                c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
                c.connect();//connect the URL Connection
                final int fileLength = c.getContentLength();
                Log.e(TAG, "fileLength " + fileLength);
                if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
                            + " " + c.getResponseMessage());

                }
                //Get File if SD card is present
                if (new CheckForSDCard().isSDCardPresent()) {
                    apkStorage = getApplicationContext().getDir(
                            "NKDROID FILES", Context.MODE_PRIVATE);
                } else
                    Toast.makeText(context, "Tidak ada SD Card.", Toast.LENGTH_SHORT).show();
                //If File is not present create directory
                if (!apkStorage.exists()) {
                    apkStorage.mkdir();
                    Log.e(TAG, "Directory Created.");
                }
                outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
                //Create New File if not present
                if (!outputFile.exists()) {
                    outputFile.createNewFile();
                    Log.e(TAG, "File Created");
                }
                FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
                InputStream is = c.getInputStream();//Get InputStream for connection
                byte[] buffer = new byte[1024];//Set buffer type
                int len1 = 0;//init length
                long total = 0;
                while (continueDownload && (len1 = is.read(buffer)) != -1) {
                    total += len1;
                    final long total_tmp = total;
                    Log.e(TAG, "progressDialog " + (total * 100 / fileLength));
                    publishProgress((int) (total * 100 / fileLength));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setProgress((int) (total_tmp * 100 / fileLength));
                        }
                    });
                    fos.write(buffer, 0, len1);//Write new file
                }
                if (!continueDownload && outputFile.exists()) {
                    try {
                        outputFile.delete();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //Close all connection after doing task
                fos.close();
                is.close();
            } catch (Exception e) {
                //Read exception if something went wrong
                e.printStackTrace();
                outputFile = null;
                Log.e(TAG, "Download Error Exception " + e.getMessage());
            }
            return null;
        }
    }
}