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

Posted

技术标签:

【中文标题】如何从对话框中取消文件下载【英文标题】:How to cancel file downloading from a dialog 【发布时间】:2018-05-26 18:59:51 【问题描述】:

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

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

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

代码:

 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;


        
    

【问题讨论】:

【参考方案1】:

只需在您的类中添加一个布尔值即可让您控制 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.setContinueDownload(false); 你应该选择你需要停止下载的地方。

以上是关于如何从对话框中取消文件下载的主要内容,如果未能解决你的问题,请参考以下文章

取消文件夹以保存已发送电子邮件的对话框提示时如何取消发送?

Android Java如何从服务中消除进度问题

如果单击保存文件对话框上的取消按钮怎么办?

如何检测何时单击文件输入的取消?

取消 QFileDialog 时如何停止子窗口关闭

取消在 JFileChooser 中选择文件而不关闭对话框