首页 > 解决方案 > 如何从对话框中取消文件下载

问题描述

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

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

我想当用户按下取消按钮时文件下载是否完成,我必须删除。请向任何人解释我该怎么做。

代码:

 public class DownloadTask {

    private static final String TAG = "Download Task";
    private Context context;

    private String downloadUrl = "", downloadFileName = "";
    private ProgressDialog progressDialog;
    public DownloadTask(Context context, String downloadUrl) {
        this.context = context;

        this.downloadUrl = downloadUrl;


        downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf( '/' ),downloadUrl.length());
        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 ((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
                }


                //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;


        }
    }
}

标签: androidandroid-layoutdialog

解决方案


只需在类中添加一个布尔值,即可控制 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;
        }
    }
}

推荐阅读