【问题标题】:Check if File Download has been interrupted检查文件下载是否被中断
【发布时间】:2014-08-04 15:04:04
【问题描述】:

我正在使用这样的 AsyncTask:

public class DownloadTask extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog;
        private Context context;
        private PowerManager.WakeLock mWakeLock;
        String fileName=null;
        public DownloadTask(Context context,ProgressDialog Dialog) {
            this.context = context;
            this.mProgressDialog=Dialog;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }


                String raw = connection.getHeaderField("Content-Disposition");

             if(raw != null && raw.indexOf("=") != -1) {
                  fileName = raw.split("=")[1];
                  fileName=fileName.split(";")[0];
                  fileName=fileName.substring(1, fileName.length()-1);
             } else {

             }
                File f=new File(context.getFilesDir()+"/"+fileName);
               if(!f.exists())
               {Log.d("TAG","DOES NOT EXIST , downloading");

                int fileLength = connection.getContentLength();

                input = connection.getInputStream();

                Log.d("Tag", raw);
                Log.d("Tag",fileName);
                output = new FileOutputStream(context.getFilesDir()+"/"+fileName);

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {

                    if (isCancelled()) {
                        input.close();
                        File check =new File(context.getFilesDir()+"/"+fileName);
                        check.delete();
                        return null;
                    }
                    total += count;

                    if (fileLength > 0) 
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            } }catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)

                    connection.disconnect();


            }
            return null;


        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                 getClass().getName());
            mWakeLock.acquire();
            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            mProgressDialog.dismiss();
            if (result != null)
                Toast.makeText(context,"Download error: "+"Please check your internet connection!", Toast.LENGTH_LONG).show();
            else
            { Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
            Intent i=new Intent(context,MuPDFActivity.class);
            Uri uri=Uri.parse(context.getFilesDir()+"/"+fileName);
            i.setAction(Intent.ACTION_VIEW);
            i.setData(uri);
            context.startActivity(i);
            }
        }}

当我从我的活动中调用它并下载文件时,这很有效。但是,如果下载中断(如果用户打开打开的应用程序列表并强制退出),部分下载的文件仍然存在,并且已损坏。 我不想继续下载,如果下载中断,我想删除文件。我怎么做?

【问题讨论】:

  • 你可以做的是,在活动onDestroy上,取消asynctask并在asynctask doinbackground中检查是否相同,如果你发现iscancel为真,只需删除文件。
  • 你确定每次都会调用 onDestroy 吗?
  • 并非总是如此,您可以通过 Android 开发人员或On This Post 找到更多信息
  • 没错,所以从 onDestroy 取消任务是不安全的,不是吗?
  • 您可以在下载完成之前显示进度对话框,或者如您所说的用户强制退出应用程序,这将调用活动的 ondestroy。

标签: java android android-asynctask httprequest


【解决方案1】:

如果用户甚至按下主页按钮或旋转您的设备,您的下载就会中断。因此,在 onStop() 方法中,您必须检查不在 onPostExecute(String result) 中的文件,因为它可能不会调用并且可能会继续下载。您可以只检查文件末尾以查看它是否具有 EOF 和 SharedPreferences 不需要。

【讨论】:

  • 我的应用只有一种方向模式,所以我至少不用担心旋转
  • 好的,但是如何使用主页按钮?您的解决方案将如何处理它?我想你不会得到结果,但你可以试试!!
  • 我使用的是asyncTask,所以后台运行的代码没有问题。只有当应用程序被强制退出时才会出现问题
【解决方案2】:

jitain sharma 取消异步任务的解决方案的想法不起作用(当强制退出应用程序时,它不会被调用)。

所以,最后,我在 AsyncTask 的 onPostExecute() 方法中使用 sharedPreferences 来“标记”文件下载的结束。我只是在检查结果,如果一切正常(那么字符串将为空),我我正在添加一个带有值为“DONE”的文件名的 SharedPreference。

在执行 AsyncTask 之前,我会检查文件是否存在以及 sharedPreference 是否存在。

public class DownloadTask extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog;
        private Context context;
        private PowerManager.WakeLock mWakeLock;
        String fileName=null;
        public DownloadTask(Context context,ProgressDialog Dialog) {
            this.context = context;
            this.mProgressDialog=Dialog;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(3000);
                connection.setConnectTimeout(5000);
                connection.connect();

                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }


                String raw = connection.getHeaderField("Content-Disposition");

             if(raw != null && raw.indexOf("=") != -1) {
                  fileName = raw.split("=")[1];
                  fileName=fileName.split(";")[0];
                  fileName=fileName.substring(1, fileName.length()-1);
             } else {

             }
                File f=new File(context.getFilesDir()+"/"+fileName);
               if(!f.exists())
               {Log.d("TAG","DOES NOT EXIST , downloading");

                int fileLength = connection.getContentLength();

                input = connection.getInputStream();

                Log.d("Tag", raw);
                Log.d("Tag",fileName);
                output = new FileOutputStream(context.getFilesDir()+"/"+fileName);

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {

                    if (isCancelled()) {
                        input.close();
                        File check =new File(context.getFilesDir()+"/"+fileName);
                        check.delete();
                        return null;
                    }
                    total += count;

                    if (fileLength > 0) 
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            } }catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)

                    connection.disconnect();


            }
            return null;


        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                 getClass().getName());
            mWakeLock.acquire();
            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            mProgressDialog.dismiss();
            if (result != null)
            {File file=new File(context.getFilesDir()+File.separator+fileName);
            file.delete();
                Toast.makeText(context,"Download error: "+"Please check your internet connection!", Toast.LENGTH_LONG).show();
            }
    //**THIS IS THE CHANGE**           else
            { SharedPreferences p=PreferenceManager.getDefaultSharedPreferences(context);
            Editor editor=p.edit();
           editor.putString(fileName, "DONE");
           editor.commit();


                    Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
            Intent i=new Intent(context,MuPDFActivity.class);
            Uri uri=Uri.parse(context.getFilesDir()+"/"+fileName);
            i.setAction(Intent.ACTION_VIEW);
            i.setData(uri);
            context.startActivity(i);
            }
        }}

这是我的检查方式:

if(!file.exists()||!PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).contains(fileName))

{ 新文件(getFilesDir()+File.separator+"phychap1.pdf").delete(); }

我总是乐于接受更好的解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多