检查文件下载是否被中断

3

我正在使用类似于以下方式的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);
            }
        }}

当我从我的活动中调用它时,这实际上是有效的,并且文件已经被下载。但是,如果下载被中断(如果用户打开打开应用程序列表并强制退出),部分下载的文件将保留下来,并且是损坏的。我不想恢复下载,我想在下载被中断时删除该文件。我该怎么做?


你可以在activity的onDestroy方法中取消asynctask并在asynctask的doinbackground方法中检查是否已经被取消,如果发现iscancel为true,就删除文件。 - jitain sharma
你确定onDestroy方法每次都会被调用吗? - harveyslash
并不总是能在 Android 开发者或此帖子中找到更多信息。 - jitain sharma
你可以在下载完成之前显示进度对话框,或者像你所说的用户强制退出应用程序,这将调用活动的ondestroy方法。 - jitain sharma
无论如何,我想要的事情不可能发生。请参见 https://dev59.com/12gu5IYBdhLWcg3wP0tm#11474271。 - harveyslash
显示剩余2条评论
2个回答

1
如果用户按下主页按钮或旋转设备,您的下载将被中断。因此,在onStop()方法中,您必须检查文件,而不是在onPostExecute(String result)中,因为它可能不会被调用,也可能继续下载。您只需检查文件的结尾是否有EOF即可,不需要使用SharedPreferences。

我的应用程序只有一种方向模式,所以我不需要担心旋转。 - harveyslash
好的,但是主页按钮怎么办?你的解决方案会如何处理它?我认为你可能不会得到结果,但你可以尝试一下!! - mmlooloo
我正在使用AsyncTask,因此代码在后台运行没有问题。只有当应用程序被强制退出时才会出现问题。 - harveyslash

0

jitain sharma的取消asynctask的解决方案没有起作用(当强制退出应用程序时,它不会被调用)。

因此,最终我在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))

{ new File(getFilesDir()+File.separator+"phychap1.pdf").delete(); }

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接