应用程序终止或销毁时文件下载不完整

时间:2018-12-20 06:34:40

标签: java android

如果我是从服务器下载文件的,如果我杀死或销毁了该应用程序,则意味着它将仅下载一半的数据,以便在应用程序打开时继续恢复下载或删除文件中不完整的数据。

有什么想法吗?

private void downloadBookDetails(String pMainFolder, String pFileName, String pDownloadURL) {
    Log.i(TAG, "Coming to this downloadBookDetails ");
    try {
        URL url = new URL(pDownloadURL);
        URLConnection ucon = url.openConnection();
        ucon.setReadTimeout(5000);
        ucon.setConnectTimeout(10000);


        InputStream is = ucon.getInputStream();
        BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

        File directory = new File(pMainFolder, pFileName);
        FileOutputStream outStream = new FileOutputStream(directory);
        byte[] buff = new byte[5 * 1024];

        int len;
        while ((len = inStream.read(buff)) != -1) {
            outStream.write(buff, 0, len);
        }


        outStream.flush();
        outStream.close();
        inStream.close();
    } catch (Exception e) {
        //Add Network Error.
        Log.e(TAG, "Download Error Exception " + e.getMessage());

        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:1)

您应使用DownLoad Manager在应用程序中进行下载。这将自动为您处理所有事情。这是一项系统服务,可以处理长时间运行的HTTP下载。

更新

如果要自己下载文件,则可以按以下方式使用它:

@SuppressLint("Wakelock")
@Override
protected String doInBackground(String... sUrl) {
    // take CPU lock to prevent CPU from going off if the user 
    // presses the power button during download
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
         getClass().getName());
    wl.acquire();

    try {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            File SDCardRoot = Environment.getExternalStorageDirectory();                    
            File file = new File(SDCardRoot,"/"+fileName);
            int downloaded=0;
            if(file.exists()){
                downloaded=(int) file.length();
                connection.setRequestProperty("Range", "bytes=" + (int) file.length() + "-");
            }
            else{
                file.createNewFile();
            }
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report 
            // instead of the file


            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength()+(int)file.length();
            // download the file
            input = connection.getInputStream();      
            if(downloaded>0){
                output = new FileOutputStream(file,true);
            }
            else{
                output = new FileOutputStream(file);
            }
            byte data[] = new byte[1024];
            long total = downloaded;
            int count;
            mProgressDialog.setMax(fileLength/1024);
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled())
                    return null;
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int)total/1024);
                output.write(data, 0, count);
            }
            output.flush();
            if (output != null)
                output.close();
            if (input != null)
                input.close();
            if (connection != null)
                connection.disconnect();
            wl.release();
            return null;
        } catch (Exception e) {
            return e.toString();
        }
    }
    catch (Exception e) {
        return e.toString();
    }        
}